How does canvas set width and height? How many ways are there?

Canvas Canvas default width 300px high 150px property set width and height

<canvas id="canvas"width="400"height="400">
Copy the code

Js sets the width and height

 let canvas = document.getElementById('canvas')
 let context = canvas.getContext('2d')
 let cx = canvas.width = 400
 let cy = canvas.height = 400
Copy the code

Do not set the width and height in the CSS

The CSS style width and height does not change the width and height of the canvas. Instead, it is scaled in proportion to its original base size. The default width of the canvas is 300 and its height is 150. The size of the elements in it increases exponentially. So the canvas width and height set in the style will scale equally, and the width and height set in the inline is the actual size of the canvas

How to deal with compatibility of Canvas in low browser?

<canvas id="c1" width="400" height="400">
	<span>Canvas browser is not supported</span>
</canvas>
Copy the code

A tag is nested inside the canvas. When encountering an unsupported canvas tag, the span will be read directly

The border of an element drawn on a canvas (left,top is an integer) is always 1 pixel. Why is it 2 pixels when placed on a canvas?

let oC = document.getElementById('c1')
let oGC = oC.getContext('2d')
oGC.strokeRect(50.50.100.100)
Copy the code

Drawing on a canvas is the same as drawing on a page. Since each point is a pixel, when its LEF is 50, since it is a 1-pixel border, it has to divide 0.5 pixel to the left and 0.5 pixel to the right around the 50-pixel line, extending from the center to the sides, so that each side has half a pixel in one pixel. This will make the page display problematic. Because pixels are displayed in a grid, not half a grid. So in this case, the computer automatically adds half a pixel, so it looks like two pixels. Processing method

oGC.strokeRect(50.5.50.5.100.100);
/ / or
oGC.strokeRect(49.5.49.5.100.100);
Copy the code

Shift the left and top by 0.5 pixel, so that when you extend from the center to the sides, it is 0.5, exactly aligned with the pixel, exactly 1 pixel.