1

I've just started learning HTML canvas, and i can't even make the simplest functionality work properly. fillRect() produces odd results, that are inconsistent with the documentation and a tutorial that i watched.

Here is the 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>

The Javascript:

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

And here is the completely messed-up result:

enter image description here

As you can see, both the y coordinate and the height are completely wrong. I've tried playing with it, tried both Chrome and Firefox- same result.

What am i missing here?

i.brod
  • 3,993
  • 11
  • 38
  • 74
  • Possible duplicate of [Wrong rectangle size in canvas](https://stackoverflow.com/questions/9286483/wrong-rectangle-size-in-canvas) – Nuwan Alawatta Jul 20 '18 at 20:15

1 Answers1

2

Adding a width & height attribute to your <canvas> html element should fix the problem. More info

Ex: <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>
doppler
  • 795
  • 5
  • 9
  • It fixed it. But how come setting the width and height by CSS didn't help? – i.brod Jul 20 '18 at 20:26
  • The default width/height is 300x150. Changing the css only stretches it the new value. You can use the HTML attribute to alter the default value, or use JS to change the elements base value – doppler Jul 20 '18 at 20:58