canvas绘制抛物线代码实例
分类:实例代码
canvas绘制抛物线代码实例属于前端实例代码,有关更多实例代码大家可以查看。
分享一段代码实例,它实现了利用canvas绘制抛物线的功能。
点击页面的一个点即可开始绘制过程。
代码实例如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <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绘制抛物线代码实例就介绍到这了。