简体   繁体   中英

How to draw Bezier curves with native Javascript code without ctx.bezierCurveTo?

I need to draw and get coordinates of bezier curves of each steps with native Javascript without ctx.bezierCurveTo method.

I found several resources, but I confused. Esspecially this looks pretty close, but I couldnt implemented clearly.

How can I accomplish this?

You can plot out the Bezier:

bezier = function(t, p0, p1, p2, p3){
  var cX = 3 * (p1.x - p0.x),
      bX = 3 * (p2.x - p1.x) - cX,
      aX = p3.x - p0.x - cX - bX;

  var cY = 3 * (p1.y - p0.y),
      bY = 3 * (p2.y - p1.y) - cY,
      aY = p3.y - p0.y - cY - bY;

  var x = (aX * Math.pow(t, 3)) + (bX * Math.pow(t, 2)) + (cX * t) + p0.x;
  var y = (aY * Math.pow(t, 3)) + (bY * Math.pow(t, 2)) + (cY * t) + p0.y;

  return {x: x, y: y};
},

(function(){
  var accuracy = 0.01, //this'll give the bezier 100 segments
      p0 = {x: 10, y: 10}, //use whatever points you want obviously
      p1 = {x: 50, y: 100},
      p2 = {x: 150, y: 200},
      p3 = {x: 200, y: 75},
      ctx = document.createElement('canvas').getContext('2d');

  ctx.width = 500;
  ctx.height = 500;
  document.body.appendChild(ctx.canvas);

  ctx.moveTo(p0.x, p0.y);
  for (var i=0; i<1; i+=accuracy){
     var p = bezier(i, p0, p1, p2, p3);
     ctx.lineTo(p.x, p.y);
  }

  ctx.stroke()
})()

Here's a fiddle http://jsfiddle.net/fQYsU/

Here is a code example for any number of points you want to add to make a bezier curve. Here points you will pass is an array of objects containing x and y values of points. [ { x: 1,y: 2 } , { x: 3,y: 4} ... ]

function factorial(n) {
    if(n<0)    
        return(-1); /*Wrong value*/      
    if(n==0)    
        return(1);  /*Terminating condition*/    
    else    
    {    
        return(n*factorial(n-1));        
    }
}

function nCr(n,r) {
    return( factorial(n) / ( factorial(r) * factorial(n-r) ) );
}

function BezierCurve(points) {
    let n=points.length;
    let curvepoints=[];
    for(let u=0; u <= 1 ; u += 0.0001 ){

        let p={x:0,y:0};

        for(let i=0 ; i<n ; i++){
            let B=nCr(n-1,i)*Math.pow((1-u),(n-1)-i)*Math.pow(u,i);
            let px=points[i].x*B;
            let py=points[i].y*B;
            
            p.x+=px;
            p.y+=py;
            
        }

        curvepoints.push(p);
    }
    
    return curvepoints;
}

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