简体   繁体   English

如何在JavaScript中创建贝塞尔曲线?

[英]how to create bezier curve in JavaScript?

I am trying to create a bezier curve using JavaScript on a HTML5 canvas. 我正在尝试在HTML5画布上使用JavaScript创建贝塞尔曲线。 Below is the code that I have written us in the drawbeziercurve function. 以下是我在drawbeziercurve函数中编写的代码。 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: 请检查此URL,它正在正确解释该过程:

http://devmag.org.za/2011/04/05/bzier-curves-a-tutorial/ 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. 您可以使用类似的方法,但是可以选择使用自己的逻辑,而不是选择随机的x和y值。

Here's a working example on jsFiddle. 这是jsFiddle上的一个工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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