javascript - 无法通过 HTML 在屏幕上显示 Canvas

标签 javascript html canvas

在我的代码中,我只得到定义宽度和高度的黑色 Canvas 。并且红色和白色未在屏幕上呈现。

提前致谢。

var canvas;
var canvasContext;
var ballx = 50;

window.onload = function() {
  canvas = document.getElementById('gameCanvas');
  canvasContext = canvas.getContext('2d');
  drawCanvas();
  drawCanvasRed();
  // drawCanvas();
}

function drawCanvas() {
  canvasContext.fillStyle = 'black';
  canvasContext.fillRect(0, 0, canvas.width, canvas.height);


  canvasContext.fillStyle = 'white';
  canvasContext.fillRect(225, 200, 50, 25);
};

function drawCanvasRed() {
  canvasContext.fillStyle = 'red';
  canvasContext.fillRect(ballx, 200, 50, 25);
}
#gameCanvas {
  width: 500px;
  height: 500px;
}
<canvas id="gameCanvas"></canvas>

最佳答案

您需要检查 Canvas 的大小。我改变了一些尺寸。所以它可以帮助你。

<!DOCTYPE html>
<html>
   <head></head>
   <style>
      #gameCanvas {
      width: 1000px;
      height: 1000px;
      }
   </style>
   <body>
      <canvas id="gameCanvas"></canvas>
      <script>
         var canvas;
         var canvasContext;
         var ballx = 50;

         window.onload = function() {
           canvas = document.getElementById('gameCanvas');
           canvasContext = canvas.getContext('2d');
           drawCanvas();
           drawCanvasRed();
           // drawCanvas();
         }

         function drawCanvas() {
           canvasContext.fillStyle = 'black';
           canvasContext.fillRect(0, 0, 500, 500); // In your size you need to check, because you passed canvas width and canvas height

           canvasContext.fillStyle = 'white';
           canvasContext.fillRect(10, 10, 50, 25);
         };

         function drawCanvasRed() {

           canvasContext.fillStyle = 'red';
           canvasContext.fillRect(ballx, 50, 50, 25);
         }
      </script>
   </body>
</html>

关于javascript - 无法通过 HTML 在屏幕上显示 Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59320915/

相关文章:

html - 如何让 CSS 列中的标题与其段落保持一致

javascript - 使用 Javascript 在 HTML5 Canvas 中随机化 RGB,为每个 fillRect 设置一个新值

javascript - 如何在 knockout 中向可观察数组中的对象添加属性并触发通知?

html - 如何让导航栏在较小的浏览器上出现在两行上?

javascript - 如何同时旋转 Canvas 中的 2 个矩形?

javascript - 是否可以使我的粒子可点击?

javascript - 是否可以在 Mocha 测试中使用 ES6 模块?

javascript - 如何将静态字符串添加到受信任的 ng-src?

javascript - 类型错误:从函数调用时 null 不是对象

javascript - 为什么同步 sleep 功能不会因为在 promise 中而变得异步?