canvas繪製拋物線程式碼例項

antzone發表於2018-06-29

分享一段程式碼例項,它實現了利用canvas繪製拋物線的功能。

點選頁面的一個點即可開始繪製過程。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head>
<body>
<canvas></canvas>
<script>
(function() {
  var W = innerWidth,
    H = innerHeight;
  var cvs = document.querySelector("canvas"),
    ctx = cvs.getContext("2d"),
    isCast = false;
 
  cvs.width = W;
  cvs.height = H;
 
  function Parabola(x0, y0, x1, y1, vx, a) {
    var x = x1 - x0,
      y = y1 - y0;
    this.x0 = x0;
    this.y0 = y0;
    this.x1 = x1;
    this.y1 = y1;
    this.a = a || 0.002;
    this.b = (y - this.a * x * x) / x;
    this._x = 0;
    this.vx = (((x1 - x0) >> 31) * 2 + 1) * vx;
    this.radius = 5;
  }
 
  Parabola.prototype.cast = function(ctx) {
    var x = (this._x += this.vx),
      y = this.a * x * x + this.b * x,
      isArrived = Math.abs(x + this.x0 - this.x1) < Math.abs(this.vx);
    ctx.beginPath();
    isArrived ? ctx.arc(this.x1, this.y1, this.radius, 0, Math.PI * 2, true)
    : ctx.arc(x + this.x0, y + this.y0, this.radius, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.stroke();
 
    return !isArrived;
  };
 
  document.addEventListener("click", function() {
    if (isCast) return;
    var x0 = Math.random() * W,
      y0 = Math.random() * H,
      x1 = Math.random() * W,
      y1 = Math.random() * H,
      radius = 5,
      parabola = new Parabola(x0, y0, x1, y1, 5);
 
    isCast = true;
 
    ctx.fillStyle = "red";
    ctx.beginPath();
    ctx.arc(x0, y0, radius, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fill();
 
    ctx.fillStyle = "blue";
    ctx.beginPath();
    ctx.arc(x1, y1, radius, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fill();
 
 
    function render() {
      if (parabola.cast(ctx)) {
        requestAnimationFrame(render);
      } else {
        isCast = false;
      }
    }
 
    render();
  }, false);
 
})();
</script>
</body>
</html>

相關文章