Let’s first understand the width and height of the canvas
canvas.width Is the size of the canvas, and canvas.style.width Is the size of the canvas rendered by the browser
First question: the height and width of the canvas
The width and height of the canvas must be set in the canvas label. If it is set in the CSS style, it will not work. The canvas will be displayed according to the default size of width: 300px, height: 150px
//Set the width and height in the label <canvas id="canvas" width="324" height="622" >
In addition to setting the canvas label directly, you can also set it when drawing. Note that the width and height of the canvas do not need units
canvas.width = 324; canvas.height = 622;
The second problem: the drawing is enlarged and the image is blurred
This is because the device independent pixels and physical pixels of mobile phones are inconsistent. The device pixel ratio = physical pixels / device independent pixels, and the device pixel ratio of most mobile phones is 2, which means that 100px images can be displayed normally only in 200px
The device pixel ratio can be obtained by using devicepixel ratio. After obtaining the pixel ratio, we can control the scaling ratio of graphics
scale = window.devicePixelRatio;
Just said, canvas.style.width It’s the size of the canvas rendered by the browser. In order to display the graphics correctly and clearly in the canvas, you need to set the correct size style.width and style.height As shown in the figure below, pay attention to adding units.
canvas.style.width = canvas.width / scale + 'px'; canvas.style.height= canvas.height/ scale + 'px';
Above, we set the width of the canvas to 324, if you do not set the style.width , the drawing will be magnified to 2 times.
This article on the canvas drawing is enlarged and fuzzy solution to this, more relevant canvas map is enlarged and fuzzy content, please search the previous articles of developeppaer or continue to browse the relevant articles below, I hope you will support developeppaer more in the future!