Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do figures appear distorted on canvas?

I'm playing around with html5 canvas, and I have came across some strange behaviour. I'm doing pretty basic animation based on these three steps:

  1. I call update() function inside wich I change x and y of the objects.
  2. I clear the canvas with this line of code this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  3. I redraw all the elements.

This is how I draw the figures:

// drawing a circle
function drawCircle(x,y) {
    var rad = 5;
    ctx.beginPath();
    ctx.arc(x, y, rad, 0, 2 * Math.PI);
    ctx.closePath();
    ctx.fill();
}

// and a rect
function drawRect(x, y,) {
     var width = 60,
       height = 10;
    ctx.fillRect(x, y, width, height);
}

Now I expect my rectangle to be 60px width and 10px height. I've added a div after the <canvas> tag and set its width and height to 60px and 10px respectively in order to illustrate the discrepancy. As you can see on the picture, obviously my rectangle isn't 60х10. The same apply to the circle. What am I missing here? enter image description here

here is fiddle

like image 435
dKab Avatar asked Nov 05 '25 21:11

dKab


2 Answers

Set the size of the canvas using it's width and height attributes (for tag) or properties (in JS):

<canvas id="..." width=400 height=400></canvas>

in JS:

canvasEl.width = 400;
canvasEl.height = 400;

Don't use CSS as that only affects the canvas element but not its bitmap (consider canvas as an image). The default size of a canvas is 300 x 150 pixels. If you don't change that size it will be stretched to the size you set using CSS. This is why we in general don't recommend using CSS (there are special cases though where CSS is necessary such as print situations, non 1:1 pixel aspect ratios and so forth).

Probably it's because you styled your canvas to a costum with/height. A canvas' default width/height is 150*300 and if you do not scale well you obtain such result as you found.

drawImage(image, x, y, width, height)
    This adds the width and height parameters, which indicate the size to which to 
    scale the image when drawing it onto the canvas.

So to be short you have to scale your drawings.

the Canvas element on MDN

Canvas drawing on MDN

like image 34
edoput Avatar answered Nov 07 '25 11:11

edoput



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!