When we resize the canvas, we want the drawing in the canvas to stay the same, just to change the size of the canvas itself. However, if you use CSS to set the canvas size, the problem occurs.
Problem description
Setting the size of the canvas canvas with CSS causes the canvas to scale proportionally to the value you set.
Reason
There is an object named 2d Rendering environment (2d redering context) within the canvas element, so it can be a strange effect to set the canvas size with CSS.
Solution
Sets the canvas size through HTML. You can set the size of the canvas element directly on the HTML page:
<canvas id="testCanvas" width="200" height="100"></canvas>
You can also set the canvas size through JS:
var canvas = document.getElementById("testCanvas"); canvas.width = 200; canvas.height = 100;
Both of these methods are OK.
Example
First we create a canvas with a width of 200px and a height of 100px, and its border is red. Then, in the middle, draw a square size of 20*20:
Code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="testCanvas"></canvas>
<script>
var canvas, context;
canvas = document.getElementById("testCanvas");
canvas.width = 200;
canvas.height = 100;
canvas.style.border = "1px solid red";
context = canvas.getContext("2d");
context.strokeStyle = "#99cc33";
context.fillRect(90, 40, 20, 20);
</script>
</body>
</html>
Reduce the canvas size by 1 time times
use CSS to set the canvas size
Related code
Canvas.style.width = "100px"; Canvas.style.height = "50px";
Effect
Analysis
We found the canvas as a whole scaled down by 1 time times.
use JS to set the canvas size
Related code
Canvas.width = m;
Canvas.height = m;
When you set the canvas size, all the styles are reset. It is therefore necessary to redraw the square
Context.fillrect (90, 40, 20, 20);
Effect
Analysis
It is the equivalent of removing the right half of the canvas and the lower half, to the desired effect.