Marin Horvat
Marin Horvat

Reputation: 79

Drawing curved lines in canvas

Is it possible to draw curved lines in canvas by their equations? If so, how? Let's say that I have math equation y=0,5*x^2 , how to print equation's graph?

I tried using bezierCurveTo and quadraticCurveTo methods unsuccessfully.

Upvotes: 0

Views: 2994

Answers (1)

Khanh Nguyen
Khanh Nguyen

Reputation: 11134

You need to populate the array of points, then use moveTo and lineTo to draw it. Something like this

var x1 = 0; // Minimum x
var x2 = 10; // Maximum x
var xstep = 0.1; // How smooth the curve should be
// ctx is the context object
// You may want to apply some transformations to the coordinate system
for (var x = x1; x < x2; x += xstep) {
    var y = 0.5 * x * x;
    if (x == x1) { 
         ctx.moveTo(x, y); // First point
    } else {
         ctx.lineTo(x, y); // Subsequent points
    }
}

ctx.stroke();

bezierCurveTo, quadraticCurveTo, and the like have fixed equation form. I am not sure if they can be used to draw parabolas, but arbitrary curves are out of question.

Upvotes: 4

Related Questions