var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d');
function Particle(x, y, vx, vy, color) { this.x = x; this.y = y; this.vx = vx; this.vy = vy; this.color = color; } Particle.prototype.update = function() { this.x += this.vx; this.y += this.vy; } Particle.prototype.draw = function() { ctx.fillStyle = this.color; ctx.fillRect(this.x, this.y, 5, 5); } var particles = []; for (var i = 0; i < 100; i++) { var x = Math.random() * canvas.width; var y = Math.random() * canvas.height; var vx = Math.random() * 2 - 1; var vy = Math.random() * 2 - 1; var color = 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')'; particles.push(new Particle(x, y, vx, vy, color)); } function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < particles.length; i++) { particles[i].update(); particles[i].draw(); } requestAnimationFrame(animate); } animate();
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com