HOWTO: Get crisp lines on your canvas tag
By default html5
canvas
anti-aliases lines that you draw and this can make
them appear to be thicker than they really are.
You can avoid this if you prefer and get crisp lines by offsetting your
coordinates to the nearest half pixel - eg
(10.5,5.5). This, however, takes working out to get the nearest half pixel
so instead, RGraph translates thecanvas
in the
constructor by half a pixel in both the X and Y directions. You can then
simply round your values (with Math.round
) to
whole numbers. This achieves the same effect.
The original un-altered line
Here is the original line drawn normally without any anti-alias fix applied.
<script> window.onload = function () { var canvas = document.getElementById("cvs"); var context = canvas.getContext('2d'); context.beginPath(); context.moveTo(125, 20); context.lineTo(125, 230); context.stroke(); } </script>
The line after the anti-alias fix has been applied
And here is the line after the fix has been applied. Initially, thecanvas
is translated by half a pixel in both
the X and Y directions and then the coordinates used are rounded so that
they're always whole values. In effect, this means
that the coordinates are "in-between" pixels but because thecanvas
has
been translated whole numbers can be used.
The line on the left is the one without any anti-alias so
that you can easily compare the two resulting lines.
<script>
window.onload = function ()
{
var canvas = document.getElementById("cvs");
var context = canvas.getContext('2d');
context.beginPath();
context.translate(0.5,0.5);
context.moveTo(125, 20);
context.lineTo(125, 230);
context.stroke();
}
</script>