canvas繪製拋物線程式碼例項
分享一段程式碼例項,它實現了利用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>
相關文章
- canvas繪製扇形程式碼例項Canvas
- canvas繪製星星程式碼例項Canvas
- canvas 繪製雞蛋程式碼例項Canvas
- canvas繪製貝濟埃曲線程式碼例項Canvas線程
- canvas繪製網格程式碼例項Canvas
- canvas繪製笑臉程式碼例項Canvas
- canvas繪製圓環效果程式碼例項Canvas
- js小球拋物線效果程式碼例項JS
- canvas繪製米字旗程式碼例項Canvas
- canvas繪製箭頭效果程式碼例項Canvas
- canvas繪製機器貓程式碼例項Canvas
- canvas繪製夜空小屋效果程式碼例項Canvas
- canvas繪製鐘錶效果程式碼例項Canvas
- canvas繪製圓角矩形程式碼例項Canvas
- canvas繪製橢圓效果程式碼例項Canvas
- canvas繪製熊貓頭像程式碼例項Canvas
- canvas繪製魚吃豆效果程式碼例項Canvas
- canvas繪製雪花飄落效果程式碼例項Canvas
- canvas繪製圓形鐘錶程式碼例項Canvas
- canvas繪製實心圓形程式碼例項Canvas
- canvas繪製網狀圓圈程式碼例項Canvas
- canvas繪製機器貓頭像程式碼例項Canvas
- canvas繪製矩形並填充顏色程式碼例項Canvas
- canvas繪製憤怒小鳥形象程式碼例項Canvas
- HTML5利用canvas繪製矩形程式碼例項HTMLCanvas
- canvas繪製五角星程式碼例項Canvas
- js按住滑鼠繪製線條程式碼例項JS
- canvas繪製帶有刻度的座標系程式碼例項Canvas
- canvas小球拋物線運動Canvas
- css繪製圓形程式碼例項CSS
- svg繪製半圓程式碼例項SVG
- canvas線性漸變程式碼例項Canvas
- canvas螞蟻線效果程式碼例項Canvas
- highcharts繪製折線資料圖程式碼例項
- canvas 繪製線條Canvas
- canvas繪製直線Canvas
- SVG拖動繪製矩形程式碼例項SVG
- jQuery繪製網格效果程式碼例項jQuery