标签:new var type console htm 函数 math val speed
canvas小球的动画
我用canvas画布实现的小球动画效果,可以参考下
我用canvas画布实现的小球动画效果,可以参考下
我用canvas画布实现的小球动画效果,可以参考下
我用canvas画布实现的小球动画效果,可以参考下
我用canvas画布实现的小球动画效果,可以参考下
js是面向对象写的
步骤:
先写好封装的函数
Random 随机数
suanzi是小球碰撞后运行方向
dong是canvas画的随机圆
·························································································································
再去new这个构造函数,我一次性for循环new200个球,多少都可以,canvas性能可以的,换js写就会卡炸
弄个定时器,随便时间,setInterval.每次执行清除画布,再重构重新200个球,就有换球的效果了,看上去球就动了
每次都是canvas画的球,所以没有DOM,不会卡顿,性能杠杠的,有兴趣的可以试试吧
细节可以看代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 7 12 </head> 13 <body> 14 <canvas id="wa" width="800" height="400"></canvas> 15 16 </body> 17 </html> 18 <script> 19 20 var hb = wa.getContext(‘2d‘); 21 var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]; 22 23 var hb=wa.getContext(‘2d‘); 24 25 function Random(max, min) { 26 return parseInt(Math.random() * (max - min) + min) 27 } 28 function Run() { 29 var r = Random(40, 20); 30 this.x = Random(wa.width - r, r); 31 this.y = Random(wa.height - r, r); 32 this.z = r; 33 this.c = ‘rgba(‘ + Random(255, 0) + ‘,‘ + Random(255, 0) + ‘,‘ + Random(255, 0) + ‘,‘ + Math.random().toFixed(1) + ‘)‘; 34 this.speedx = Random(10, -10); 35 this.speedy = Random(5, -5) 36 } 37 38 Run.prototype.suanzi = function () { 39 40 if (this.speedx == 0) { 41 this.speedx = 6; 42 } 43 if (this.speedy == 0) { 44 this.speedy = -4; 45 } 46 47 if (this.x < this.z || wa.width - this.z < this.x) { 48 this.speedx *= -1; 49 } 50 if (this.y < this.z || wa.height - this.z < this.y) { 51 this.speedy *= -1; 52 } 53 this.x += this.speedx; 54 this.y += this.speedy; 55 }; 56 57 Run.prototype.dong = function () { 58 59 hb.beginPath(); 60 hb.arc(this.x, this.y, this.z, 0, Math.PI * 2); 61 62 hb.fillStyle = this.c; 63 hb.fill(); 64 hb.closePath(); 65 66 }; 67 68 69 var palys = []; 70 for (var i = 0; i < 200; i++) { 71 var play = new Run(); 72 play.dong(); 73 palys.push(play); 74 } 75 76 setInterval(function () { 77 hb.clearRect(0, 0, wa.width, wa.height); 78 for (var j = 0; j < palys.length; j++) { 79 palys[j].suanzi(); 80 palys[j].dong(); 81 console.log(palys[0]) 82 } 83 }, 10); 84 85 86 </script>
标签:new var type console htm 函数 math val speed
原文地址:http://www.cnblogs.com/wang1048076313/p/6882645.html