When we draw a line in canvas, the default line width is 1px and the color is black. But we will find that the width of the line is wider than 1px, the color is not so black, more like gray. Let's see the effect.
Code:
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> canvas { border: 1px solid #000; } </style> </head> <body> <canvas id="mycanvas" width="200" height="200"></canvas> </body> </html> <script> var mycanvas = document.getElementById('mycanvas'); var ctx = mycanvas.getContext('2d'); ctx.moveTo(50,50); ctx.lineTo(150,50); ctx.stroke() </script>
Effect:
We set the border to 1px, and the default line is 1px, but we found that the line is lighter than the border.
Why does this effect occur?
Reason:
As shown in the figure, our computer screen is made up of pixels. When we start drawing a line horizontally at (0,0) coordinates, canvas will find the center of the y axis 0px scale 0.5px to start drawing. The width of the line is 0.5px to 1.5px, but because the minimum unit of resolution pixel is 1px, the browser will resolve 0.5px to 1px. Make the line 2px. The color will also fade. It's like a bottle of ink, half filled with ink and half diluted with water, so the color will fade. The solution is to move the movaToy axis up and down by 0.5px.
Contrast code:
<style> canvas { border: 1px solid #000; } </style> </head> <body> <canvas id="mycanvas" width="200" height="200"></canvas> </body> </html> <script> var mycanvas = document.getElementById('mycanvas'); var ctx = mycanvas.getContext('2d'); ctx.moveTo(50,50); ctx.lineTo(150,50); //y axis +0.5 ctx.moveTo(50,50.5); ctx.lineTo(200,50.5); ctx.stroke() </script>
Comparison map:
But we can ignore this defect in the drawing.