问题描述:

This question already has an answer here:

  • Canvas is stretched when using CSS but normal with “width” / “height” properties

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

网友答案:

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>
网友答案:

There doesn't seem to be anything wrong with the way you have written. Have you checked if you have linked the CSS file correctly?

I usually add something like

border: 1px solid;

to my css to let me figure out the width and height. You can check my fiddle

网友答案:

canvas element has height and width attributes. Assign values through javascript code:

var canvas = document.getElementsByTagName('canvas')[0];
canvas.width  = 100;
canvas.height = 100;

As for your question, it's because the only thing that you resize through css is the "container" of the canvas, not the size of the canvas itself. When you try to draw on the canvas with the "container" size bigger than the size of the canvas itself the image will look blurry.

相关阅读:
Top