Javascript bezier curves

Date: 2019-06-19

https://www.jasondavies.com/animated-bezier/

// @NK: converted the code below to ES6 function
const pow = Math.pow;
const calc = (x0, x1, x2, x3) => {
    const c = 3 * (x1 - x0),
          b = 3 * (x2 - x1) - c,
          a = x3 - x0 - c - b;
    return (t) => (a * pow(t, 3)) + (b * pow(t, 2)) + (c * t) + x0;
};
const bezier = (p0, p1, p2, p3) => {
    const xfn = calc(p0.x, p1.x, p2.x, p3.x), 
          yfn = calc(p0.y, p1.y, p2.y, p3.y);
    return t => ({
        x: xfn(t),
        y: yfn(t)
    });
};

https://javascript.info/bezier-curve

https://stackoverflow.com/a/16227479/1052129

    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()
    })()

http://jsfiddle.net/fQYsU/

Approximate SINE function:

cubic bezier approximation compared with sinusoidal
cubic-bezier(0.364212423249, 0, 0.635787576751, 1)

https://stackoverflow.com/a/50596945

22360cookie-checkJavascript bezier curves