HTML 5 canvas:fillRect()产生完全错误的结果

时间:2018-07-20 20:09:41

标签: javascript html5-canvas

我刚刚开始学习HTML画布,我什至无法使最简单的功能正常工作。 fillRect()产生奇怪的结果,与我看过的文档和教程不一致。

这是html:

 <style>
    canvas{
        width: 500px;
        height: 500px;
        background-color: aqua;
        border: 1px solid black;
    }
</style>

<body>
   <canvas id="canvas"></canvas>
   <script src="canvas.js"></script>
</body>

JavaScript:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 100, 100);

这是完全混乱的结果:

enter image description here

如您所见,y坐标和高度都完全错误。我尝试过使用它,尝试过Chrome和Firefox,结果都一样。

我在这里想念什么?

1 个答案:

答案 0 :(得分:1)

向您的<canvas> html元素添加width和height属性应该可以解决此问题。 More info

例如:<canvas width="500" height="500"></canvas>

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 100, 100);
canvas {
  background-color: aqua;
  border: 1px solid black;
}
<body>
  <canvas id="canvas" width="500" height="500"></canvas>
  <script src="canvas.js"></script>
</body>