Skip to content

Instantly share code, notes, and snippets.

@tombowers
Created October 27, 2014 15:28
Show Gist options
  • Save tombowers/10b84bb45795b7bcf34b to your computer and use it in GitHub Desktop.
Save tombowers/10b84bb45795b7bcf34b to your computer and use it in GitHub Desktop.
HTML5 Canvas – Crisp lines every time
context.translate(0.5, 0.5);
var ctx = document.getElementById('canvas').getContext('2d');
for (var i = 0; i < 10; i++) {
var iStrokeWidth = 1 + i;
var iTranslate = (iStrokeWidth % 2) / 2;
ctx.translate(iTranslate, 0);
ctx.lineWidth = iStrokeWidth;
ctx.beginPath();
ctx.moveTo(5+i*14, 5);
ctx.lineTo(5+i*14, 140);
ctx.stroke();
// reset the translation back to zero
ctx.translate(-iTranslate, 0);
}
<canvas id="canvas" width="150" height="150"></canvas>
var iStrokeWidth = 1;
var iTranslate = (iStrokeWidth % 2) / 2;
context.translate(iTranslate, iTranslate);
var ctx = document.getElementById('canvas').getContext('2d');
for (var i = 0; i < 10; i++) {
var iStrokeWidth = 1 + i;
var iTranslate = (iStrokeWidth % 2) / 2;
ctx.translate(iTranslate, iTranslate);
ctx.lineWidth = iStrokeWidth;
ctx.beginPath();
ctx.moveTo(5+i*14, 5);
ctx.lineTo(5+i*14, 140);
ctx.stroke();
// reset the translation back to zero
ctx.translate(-iTranslate, -iTranslate);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment