The following snippet draws vertical lines on a canvas (1px width). However, some lines appear to be wider than others, some are blurry, others are ok. In different posts i've read that one needs to substract 0.5 px or translate coordinates. It doesn't work in my case.
I've tried using translate by a factor odf 0.5, rounding coordinates and manually adding 0.5 (see the variations of the drawLine method). Nothing works
How can i get the vertical lines to be crisp and clean?
thank you
function doStuff() {
var cnv = document.getElementById("cnvs");
var ctx = cnv.getContext("2d");
var lw = 1;
ctx.lineWidth = lw;
var xMax = cnv.width;
var ygMax = cnv.height;
var iTranslate = 0.5; // (lw % 2) / 2;
ctx.translate(iTranslate, iTranslate);
deltaX = 12;
for (var x = deltaX; x < xMax; x += deltaX) {
drawLine(ctx, x, ygMax, x, 0);
}
}
function drawLine(ctx, x0, y0, xf, yf) {
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(xf, yf);
ctx.stroke();
ctx.closePath();
}
function drawLine2(ctx, x0, y0, xf, yf) {
ctx.beginPath();
ctx.moveTo(Math.round(x0), y0);
ctx.lineTo(Math.round(xf), yf);
ctx.stroke();
ctx.closePath();
}
function drawLine3(ctx, x0, y0, xf, yf) {
ctx.beginPath();
ctx.moveTo(x0 + 0.5, y0);
ctx.lineTo(xf + 0.5, yf);
ctx.stroke();
ctx.closePath();
}
doStuff();
<canvas id="cnvs" width="200" height="100"></canvas>