Canvas How to - Bounce along an arc path








Question

We would like to know how to bounce along an arc path.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from w w w .j  ava 2s  .co  m-->
    var canvas = document.querySelector("canvas");
    var ctx = canvas.getContext("2d");
    var p0 = {"x": 100, "y": 100};
    var p1 = {"x": 350, "y": 50};
    var p2 = {"x": 350, "y": 400};
    var p3 = {"x": 100, "y": 350};
    var t = 0;
    var speed = 0.04;
    canvas.height = 666;
    canvas.width = 666;
    setInterval(function () {
        var at = 1 - t;
      var green1x = p0.x * t + p1.x * at;
      var green1y = p0.y * t + p1.y * at;
      var green2x = p1.x * t + p2.x * at;
      var green2y = p1.y * t + p2.y * at;
      var green3x = p2.x * t + p3.x * at;
      var green3y = p2.y * t + p3.y * at;
      var blue1x = green1x * t + green2x * at;
      var blue1y = green1y * t + green2y * at;
      var blue2x = green2x * t + green3x * at;
      var blue2y = green2y * t + green3y * at;
      var finalx = blue1x * t + blue2x * at;
      var finaly = blue1y * t + blue2y * at;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.beginPath();
      ctx.arc(finalx, finaly, 30, 0, 2 * Math.PI, false);
      ctx.fillStyle = 'red';
      ctx.fill();
      ctx.closePath();
      t += speed;
      if (t > 1 || t < 0) speed *= -1;
    }, 160);
}//]]>  
</script>
</head>
<body>
  <canvas/>

</body>
</html>

The code above is rendered as follows: