When the html5-Canvas element uses strokeRect to draw the border rectangle, the default border is 1 pixel, but the reason why the border on the page displays 2 pixels

When we use strokeRect to draw the border rectangle, the border will be 2 pixels on the page, what is the reason? (strokeRect default border is 1 pixel)

<canvas id="myCanvas" width="300"   height="300">
Your browser does not support canvas element, please upgrade your browser
</canvas
<script>
var c=document.getElementById("myCanvas");
var txt=c.getContext("2d");
txt.strokeRect(50,50,100,100);
</script>


As shown below:


(Looking at this picture, it doesn't look like 1 pixel anger, it's not 1 pixel) Why does a 1 pixel border show 2 pixels?

This is because: when Canvas draws on the page, each point of the canvas is a pixel, and when strokeRect reaches 50, it starts to draw left and right around 50, and 50 is equivalent to the center point. Explanation above:


When strokeRect reaches the line 50, it divides 0.5 pixels to the left and 0.5 pixels to the right. We know that pixels are displayed one by one, and there will be problems with displaying pixels in half a grid. In this case, the computer will automatically add another half pixel for us, so it looks like 2 pixels.

In order to avoid this problem, we can adopt the following methods:

Set the coordinates to xx.5, as follows:

txt.strokeRect(50.5,50.5,100,100);

The page shows:


For obvious comparison, I put two pictures together:




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325766161&siteId=291194637