Search code examples
javascriptcanvasblurry

Canvas element with blurred lines


I wonder why the edges/lines of my canvas element are blurred (Chrome, IE, FF) and have a so-called "sawtooth-effect" (does this expression exist in english? :-)) as you can see here: enter image description here

It is just a quick first try - maybe I did something wrong? Here is the code:

c2 = document.getElementById('test').getContext('2d');
c2.fillStyle = '#f00';
c2.beginPath();
c2.moveTo(0, 0);
c2.lineTo(100, 0);
c2.lineTo(80, 50);
c2.lineTo(0, 50);
c2.closePath();
c2.fill();

c2.fillStyle = "#000";
c2.beginPath();
c2.moveTo(0, 50);
c2.lineTo(80, 50);
c2.lineTo(60, 100);
c2.lineTo(0, 100);
c2.closePath();
c2.fill();

I also added it to this JS Fiddle


Solution

  • You can oversample the canvas (fake double resolution):

    Here's an illustration with standard resolution on top and "double" resolution on bottom:

    A Demo: http://jsfiddle.net/m1erickson/M5NHN/

    enter image description here

    Html:

    <canvas id="canvas1" width=300 height=150></canvas>
    <canvas id="canvas2" width=600 height=300></canvas>
    

    CSS:

    #canvas1 {
        border:1px solid red;
        width:300px;
        height:150px;
    }
    #canvas2 {
        border:1px solid green;
        width:300px;
        height:150px;
    }
    

    JS:

    var canvas = document.getElementById("canvas1");
    var context1 = canvas.getContext("2d");
    var canvas = document.getElementById("canvas2");
    var context2 = canvas.getContext("2d");
    
    draw(context1);
    
    context2.scale(2, 2);
    draw(context2);
    
    function draw(c2){
    
    c2.fillStyle = '#f00';
    c2.beginPath();
    c2.moveTo(0, 0);
    c2.lineTo(100, 0);
    c2.lineTo(80, 50);
    c2.lineTo(0, 50);
    c2.closePath();
    c2.fill();
    
    c2.fillStyle = "#000";
    c2.beginPath();
    c2.moveTo(0, 50);
    c2.lineTo(80, 50);
    c2.lineTo(60, 100);
    c2.lineTo(0, 100);
    c2.closePath();
    c2.fill();
    }