How to get crisp lines with no antialias

Share RGraph:   

Summary
A guide for getting crisp lines with no antialias. By default lines drawn on HTML5 canvas are antialias'ed - this HOWTO shows you how to avoid that.

By default HTML5 canvas antialiases 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 translate()s the canvas 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

[No canvas support]

Here is the original line drawn normally without any antialias 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 antialias fix has been applied

[No canvas support]

And here is the line after the the fix has been applied. Initially, the canvas 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 the canvas has been translated whole numbers can be used. The line on the left is the one without any antialias so that you can easily compare the difference of the two 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>

Comments

Add a new comment...