Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we can't set width and height for canvas using css [duplicate]

Why the canvas appears as scaled one, when the height and width is specified in css instead of DOM?

Html:

 <canvas></canvas>

Css:

 canvas{
       width:100px;
       height:100px;
    }
like image 441
albert Jegani Avatar asked Oct 31 '14 09:10

albert Jegani


2 Answers

You can set Width and Height on canvas using CSS - but,

canvas width,height attribute determines the actual pixel will be used to draw on canvas. It is used for canvas co-ordinate system.

On the other hand CSS width / height is related to box model.

By default the canvas usage 300px width and 150px height. If you set CSS width / height without setting canvas attributes that will be applied on that 300px/150px. Imagine a 300px/150px sized image where you are setting the width/height using CSS as 100px/100px. What will happen? it will distort right? same thing applied for canvas as well.

You'll find more details on HTML living standard page - https://html.spec.whatwg.org/multipage/scripting.html#attr-canvas-width

Hope that answer your question.

like image 196
Hasanavi Avatar answered Sep 28 '22 17:09

Hasanavi


so think of the canvas element to be composed of two different view.

  1. The html element(canvas).
  2. The inner drawing surface of the canvas.

First approach:

Setting the height and width of the canvas through css will only set them to the html element canvas but not to the inner drawing surface(this is generally bad practise when it comes to canvas elements).

Now usually with this approach when the element width and height is more than the default width and height of the drawing surface, what the browser does is, it scales up the drawing surface to find the canvas element size. Hence you will notice the drawing surface zoomed in.

Second approach:

Setting the height and width of the canvas through the element width and height attributes, set them to both the canvas and the drawing surface. Like so,

<canvas width="300" height="300"></canvas>
like image 33
Lakmal Caldera Avatar answered Sep 28 '22 15:09

Lakmal Caldera