本文实例讲述了JavaScript+html5 canvas制作的百花齐放效果。分享给大家供大家参考,具体如下:
运行效果截图如下:
具体代码如下:
<!DOCTYPE html><html> <head> <title>demo</title> <style type="text/css"> body { margin:0; padding:0; } #canvas { border:5px solid gray; box-shadow:0 0 15px 15px #494949 inset; margin-top:50px; margin-left:200px; } </style> </head> <body > <canvas id="canvas" width="1000px" height="500px"></canvas> <script type="text/javascript"> var dyl = {}; dyl.canvas = document.getElementById("canvas"); dyl.ctx = dyl.canvas.getContext("2d"); dyl.runTime = 0; dyl.colorList = "01234567890ABCDEFabcdef".split(""); dyl.colorListLength = dyl.colorList.length; dyl.arcList = null; /** * 得到16进制随机颜色值 */ dyl.getColor = function() { var color = "#"; for(var i=0; i<6; i++) { color += dyl.colorList[Math.floor(Math.random()*dyl.colorListLength)]; } return color; }; /** * 一个随机角度,随机初始速度的斜抛对象 */ var Arc = function(i) { // 设置自有属性 this.v = Math.round(Math.random()*100)+50; this.angle = Math.round(Math.random()*145) + 45; this.startTime = +new Date(); this._angle = this.angle/180*Math.PI; this.v_x = this.v*Math.cos(this._angle); this.v_y_start = this.v*Math.sin(this._angle); this.color = dyl.getColor(); this.x = 500; this.g = 250; this.y = 490; this.index = i; var _self = this; this.run = function() { var endTime = +new Date(); var timeSpan = (endTime - _self.startTime)/1000; var v_y_now = _self.v_y_start - 1/2*_self.g*Math.pow(timeSpan, 2); _self.x = _self.x +_self.v_x * timeSpan; _self.y = _self.y - (_self.v_y_start * timeSpan - 1/2*_self.g*Math.pow(timeSpan, 2)); return this; }; return this; }; /** * 全局绘制图像 */ dyl.draw = function() { var arcList = dyl.arcList; var ctx = dyl.ctx; dyl.runTime++; for(var i=0, length=arcList.length; i<length; i++) { var arc = arcList[i]; if(!arc) { continue; } arc.run(); ctx.save(); ctx.beginPath(); ctx.fillStyle = arc.color; ctx.arc(arc.x, arc.y, 2, 0, Math.PI*2); ctx.fill(); ctx.closePath(); ctx.restore(); } console.log(dyl.runTime); if(dyl.runTime >= 25) { setTimeout(dyl.init, 1050); } else { setTimeout(dyl.draw, 20); } }; /** * 初始化整个事件 */ dyl.init = function() { dyl.ctx.clearRect(0, 0, 1000, 500); dyl.arcList = []; dyl.runTime = 0; for(var i=0; i<100; i++) { dyl.arcList.push(new Arc(i)); } dyl.draw(); }; dyl.init(); </script> </body></html>
更多关于js特效相关内容感兴趣的读者可查看本站专题:《jQuery动画与特效用法总结》及《jQuery常见经典特效汇总》
希望本文所述对大家JavaScript程序设计有所帮助。
新闻热点
疑难解答