Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is due to the fact lines are drawn over all pixels they're over (on canvas positionning is in float). When you want to draw precise vertical or horizontal lines in javascript on a canvas, you'd better have them in half ints.</p> <p>See illustration : The first horizontal line was drawn with a y position of 1. This line is fuzzy and wide. The second horizontal line was drawn with a y position of 4.5. It is thin and precise.</p> <p><img src="https://i.stack.imgur.com/CVZi8.png" alt="enter image description here"></p> <p>For example in your code, I had good results by changing your horizontal lines loop to this :</p> <pre><code> // Horizontal lines for (var i = 1; i &lt; objCanvas.height / intGridWidth; i++) { objContext.strokeStyle = "white"; var y = Math.floor(i*intGridWidth)+0.5 objContext.moveTo(0, y); objContext.lineTo(objCanvas.width, y); objContext.stroke(); } </code></pre> <p>Here's a fiddle demonstrating it with very thin and clean lines :</p> <p><a href="http://jsfiddle.net/dystroy/7NJ6w/" rel="noreferrer">http://jsfiddle.net/dystroy/7NJ6w/</a></p> <p>The fact that a line is drawn over all pixels it is over means the only way to draw an horizontal line with a width of exactly one pixel is to target the middle. I usually have this kind of util functions in my canvas based applications :</p> <pre><code>function drawThinHorizontalLine(c, x1, x2, y) { c.lineWidth = 1; var adaptedY = Math.floor(y)+0.5; c.beginPath(); c.moveTo(x1, adaptedY); c.lineTo(x2, adaptedY); c.stroke(); } </code></pre> <p>Of course you'd better do it for vertical lines too to have a good looking page.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload