【问题标题】:Unable to get Canvas on screen via HTML无法通过 HTML 在屏幕上显示 Canvas
【发布时间】:2020-04-06 19:24:34
【问题描述】:

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

提前致谢。

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>

【问题讨论】:

  • 它有效,它们只是画布的“外部”。如果你没有定义画布的大小,它会使用 300x150px 作为默认大小。
  • @cloned 为什么要修改 OPs 代码(添加样式定义)?
  • @Andreas 画布尺寸在css文件中定义,为800x600 px
  • 这不会影响画布的实际大小 -> stackoverflow.com/questions/35219815/…
  • @Andreas。当给出内联样式时,它现在正在工作。谢谢你的解释。

标签: javascript html canvas


【解决方案1】:

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

<!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>

【讨论】:

    猜你喜欢
    • 2015-09-05
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2013-09-30
    • 2017-02-16
    • 2016-10-20
    • 2021-03-04
    相关资源
    最近更新 更多