20

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/

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
wong2
  • 34,358
  • 48
  • 134
  • 179

2 Answers2

24

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:

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

It's also faster since less drawing is done.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
17

What you're doing is creating a canvas which is the default size, 300 by 150, and then scaling it up using CSS to 1000px by 1000px. But scaling it up like that just magnifies the size of the pixels, it doesn't increase the resolution of the canvas itself. What you need to do is set the actual dimensions of the canvas itself using the width and height attributes:

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

Then you don't need to scale it up by setting canvas.style.width and height any more.

Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
  • 2
    It's still not pretty. A bezier curve might be useful (animation would be different): http://www.robodesign.ro/coding/canvas-primer/20081208/example-paths.html – Rudie May 17 '11 at 14:41
  • This solved the resizing with CSS issue, though my project required relative sizing within the canvas container div rather than hard coding pixel sizes. The following question helped with sizing by percent: https://stackoverflow.com/q/18679414/9403538 – jacob Dec 09 '22 at 17:47