Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas anti-alias?

I'm trying to draw a quadratic curve with canvas. Here is the code:
HTML:

<canvas id="mycanvas"> 
    Your browser is not supported.
</canvas> 

JavaScript:

var canvas = document.getElementById("mycanvas");
canvas.style.width = "1000px";
canvas.style.height = "1000px";
if (canvas.getContext) {
    var ctx = canvas.getContext("2d");
    var x = 0,
        y = 0;
    setInterval(function() {
        ctx.lineTo(x, y);
        ctx.stroke();
        x += 1;
        y = 0.01 * x * x;
    }, 100);
}

But the result is really ugly, first, the lines are too thick, second, the alias is so obvious.... how could I improve it?
You can see the effect here: http://jsfiddle.net/7wNmx/1/

like image 933
wong2 Avatar asked May 17 '11 14:05

wong2


1 Answers

Another thing is that you're stroking each time. So the first line is drawn most, whilst the second is drawn one less time, etc.

This also causes it to become ugly. You'd need to begin a new path and only stroke that one:

var canvas = document.getElementById("mycanvas");
canvas.style.width = "1000px";
canvas.style.height = "1000px";
if (canvas.getContext) {
    var ctx = canvas.getContext("2d");
    var x = 0,
        y = 0;
    setInterval(function() {
        ctx.beginPath();
        ctx.moveTo(x,y)
        x += 1;
        y = 0.01 * x * x;
        ctx.lineTo(x, y);
        ctx.stroke();
    }, 100);
}

Compare:

http://i.stack.imgur.com/40M20.png

It's also faster since less drawing is done.

like image 171
pimvdb Avatar answered Sep 23 '22 12:09

pimvdb