Search code examples
htmlcanvas

Canvas drawings, like lines, are blurry


I have a <div style="border:1px solid border;" /> and canvas, which is drawn using:

context.lineWidth = 1;
context.strokeStyle = "gray";

The drawing looks quite blurry (lineWidth less than one creates even worse picture), and nothing near to the div's border. Is it possible to get the same quality of drawing as HTML using canvas?

var ctx = document.getElementById("canvas").getContext("2d");
ctx.lineWidth = 1;
ctx.moveTo(2, 2);
ctx.lineTo(98, 2);
ctx.lineTo(98, 98);
ctx.lineTo(2, 98);
ctx.lineTo(2, 2);
ctx.stroke();
div {
  border: 1px solid black;
  width: 100px;
  height: 100px;
}
canvas, div {background-color: #F5F5F5;}
canvas {border: 1px solid white;display: block;}
<table>
<tr><td>Line on canvas:</td><td>1px border:</td></tr>
<tr><td><canvas id="canvas" width="100" height="100"/></td><td><div>&nbsp;</div></td></tr>
</table>


Solution

  • When drawing lines in canvas, you actually need to straddle the pixels. It was a bizarre choice in the API in my opinion, but easy to work with:

    Instead of this:

    context.moveTo(10, 0);
    context.lineTo(10, 30);
    

    Do this:

    context.moveTo(10.5, 0);
    context.lineTo(10.5, 30);
    

    Dive into HTML5's canvas chapter talks about this nicely