简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM