<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script> 
  </head>

  <body>
    <div>
      <input id="slider" type="range" min="0" max="100"/>
    </div>
    <canvas id="canvas" width="400" height="400"/>
  </body>

</html>
'use strict'

var points = [{
  x: 100,
  y: 200
}, {
  x: 200,
  y: 300
}, {
  x: 200,
  y: 100
}, {
  x: 300,
  y: 200
}, ];

//http://answers.unity3d.com/questions/12689/moving-an-object-along-a-bezier-curve.html
function bezierInterpolate(s, st, et, e, t) {
  return (((-s + 3 * (st - et) + e) * t + (3 * (s + et) - 6 * st)) * t + 3 * (st - s)) * t + s;
}

function updateView(ctx, interpolation) {

  // start/end
  var ptStart = points[0];
  var ptEnd = points[3];

  // control points
  var q1 = points[1];
  var q2 = points[2];

  // clear
  ctx.clearRect(0, 0, 400, 400);

  // frame
  ctx.strokeStyle = "black";
  ctx.strokeRect(0, 0, 400, 400);

  // position indicator
  ctx.beginPath();
  ctx.lineWidth = 1;
  ctx.strokeStyle = "blue";
  ctx.moveTo(ptStart.x, ptStart.y);
  ctx.lineTo(ptEnd.x, ptEnd.y);
  ctx.stroke();

  // curve
  ctx.beginPath();
  ctx.lineWidth = 3;
  ctx.strokeStyle = "black";
  ctx.moveTo(ptStart.x, ptStart.y);
  ctx.bezierCurveTo(q1.x, q1.y, q2.x, q2.y, ptEnd.x, ptEnd.y);
  ctx.stroke();
  
  // points
  for(var p in points) {
    var point = points[p];
    ctx.beginPath();
    ctx.fillStyle = "green";
    ctx.arc(point.x, point.y, 2, 0, Math.PI * 2);  
    ctx.fill();
  }

  // position along the curve
  var interpolatedX = bezierInterpolate(ptStart.x, q1.x, q2.x, ptEnd.x, interpolation);
  var interpolatedY = bezierInterpolate(ptStart.y, q1.y, q2.y, ptEnd.y, interpolation);

  ctx.beginPath();
  ctx.fillStyle = "red";
  ctx.arc(interpolatedX, interpolatedY, 4, 0, Math.PI * 2);
  ctx.fill();
}

$(function() {
  var slider = $('#slider');
  var canvas = $('#canvas')[0];

  slider.change(function(ev) {
    var value = slider.val() / 100.0;
    if (canvas.getContext) {
      updateView(canvas.getContext('2d'), value);
    }
  });

  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    updateView(ctx, 0.5);
  } else console.log("no context");
});
/* Styles go here */