how to draw smooth curve through N points using javascript HTML5 canvas?

后端 未结 11 659
时光说笑
时光说笑 2020-11-22 16:40

For a drawing application, I\'m saving the mouse movement coordinates to an array then drawing them with lineTo. The resulting line is not smooth. How can I produce a sing

11条回答
  •  时光取名叫无心
    2020-11-22 17:14

    If you want to determine the equation of the curve through n points then the following code will give you the coefficients of the polynomial of degree n-1 and save these coefficients to the coefficients[] array (starting from the constant term). The x coordinates do not have to be in order. This is an example of a Lagrange polynomial.

    var xPoints=[2,4,3,6,7,10]; //example coordinates
    var yPoints=[2,5,-2,0,2,8];
    var coefficients=[];
    for (var m=0; m0) {
                newCoefficients[0]=-xPoints[0]/(xPoints[m]-xPoints[0]);
                newCoefficients[1]=1/(xPoints[m]-xPoints[0]);
        } else {
            newCoefficients[0]=-xPoints[1]/(xPoints[m]-xPoints[1]);
            newCoefficients[1]=1/(xPoints[m]-xPoints[1]);
        }
        var startIndex=1; 
        if (m==0) startIndex=2; 
        for (var n=startIndex; n=1; nc--) {
            newCoefficients[nc]=newCoefficients[nc]*(-xPoints[n]/(xPoints[m]-xPoints[n]))+newCoefficients[nc-1]/(xPoints[m]-xPoints[n]);
            }
            newCoefficients[0]=newCoefficients[0]*(-xPoints[n]/(xPoints[m]-xPoints[n]));
        }    
        for (var nc=0; nc

提交回复
热议问题