简体   繁体   中英

how to create bezier curve in JavaScript?

I am trying to create a bezier curve using JavaScript on a HTML5 canvas. Below is the code that I have written us in the drawbeziercurve function. The result is that, I only get the four points, but cant get the bezier curve to appear. Any help guys?

function drawBezierCurve() {
    "use strict";
    var t, i, x, y, x0, x1, x2, x3;

    //  for (t = 1; t <= nSteps; t++) {
    //t = 1/nSteps

    q0 = CalculateBezierPoint(0, x0, x1, x2, x3);

    for(i = 0; i <= nSteps; i++)
    {
        t = i / nSteps;
        q1 = CalculateBezierPoint(t, x0, x1, x2, x3);
        DrawLine(q0, q1);
        q0 = q1;
    }

    //[x] = (1-t)³x0 + 3(1-t)²tx1+3(1-t)t²x2+t³x3
    //[y] = (1-t)³y0 + 3(1-t)²ty1+3(1-t)t²y2+t³y3

    procedure draw_bezier(A, v1, v2, D)
        B = A + v1
        C = D + v2

        //loop t from 0 to 1 in steps of .01 
        for(t=0; t <=1; t+ 0.1){
            a = t
            b = 1 - t

            point = A*b³ + 3*B*b²*a + 3C*b*a2 + D*a³  

            //drawpixel (point)
            drawLine(arrayX[0], arrayY[0], (arrayX[0] + arrayX[1] + arrayX[2] + arrayX[3]) / 4,
                (arrayY[0] + arrayY[1] + arrayY[2] + arrayY[3]) / 4, 'blue');

            //end of loop
        }

    end of draw_bezier

    /*    drawLine(arrayX[0], arrayY[0], (arrayX[0] + arrayX[1] + arrayX[2] + arrayX[3]) / 4,
        (arrayY[0] + arrayY[1] + arrayY[2] + arrayY[3]) / 4, 'blue');

    drawLine((arrayX[0] + arrayX[1] + arrayX[2] + arrayX[3]) / 4, 
        (arrayY[0] + arrayY[1] + arrayY[2] + arrayY[3]) / 4, arrayX[3], arrayY[3], 'blue');   */
}

// points array

please check this URL, it is explaining the procedure properly:

http://devmag.org.za/2011/04/05/bzier-curves-a-tutorial/

Do draw a poly-line (a line consisting of many points) on a canvas, do something like this:

var canvas = document.querySelector('canvas'),
    ctx = canvas.getContext('2d');

ctx.lineWidth = 1.5;
ctx.strokeStyle = 'red';

ctx.beginPath();
for (var i = 0; i < 100; i++)
{
    var x = Math.random() * 100,
        y = Math.random() * 100;
    ctx.lineTo(x, y);
}
ctx.stroke();

You can use something similar, however instead of choosing random x and y values, use your own logic.

Here's a working example on jsFiddle.

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