191
Pp
particle-play / files
particle-play / script.js
2.7 KB
1/* browser:true, onevar:true, eqeqeq:true, curly:true, maxlen:80 */ 2 3(function (win, doc) { 4 var body = doc.querySelector('body'), 5 canvas = doc.createElement('canvas'), 6 c = canvas.getContext('2d'), 7 xmiddle = Math.floor(win.innerWidth /2), 8 ymiddle = Math.floor(win.innerHeight /2), 9 radians = Math.PI /180; 10 11 function Particle (x, y) { 12 this.x = x; 13 this.y = y; 14 this.xVel = randomRange(0, 1); 15 this.yVel = randomRange(0, 1); 16 this.size = 20; 17 this.color = Math.floor(randomRange(0, 360)); 18 this.alpha = 1; 19 this.angle = Math.floor(randomRange(0, 360)); 20 } 21 22 Particle.prototype = { 23 update: function () { 24 this.alpha -= 0.02; 25 this.size -= 0.3; 26 this.color = this.color > 300 ? 0 : this.color +1; 27 28 this.xVel *= 1.2; 29 this.yVel *= 1.2; 30 31 this.x += this.xVel; 32 this.y += this.yVel; 33 34 if (this.x > canvas.width -10 || this.y > canvas.height -10 || 35 this.size <= 0 || this.angle > 360) { 36 37 /* I'm pretty sure this is not the right way to do this, but 38 it's working... Correct me please */ 39 Particle.call(this, Math.floor(randomRange(0, win.innerWidth)), 40 Math.floor(randomRange(0, win.innerHeight))); 41 42 } 43 }, 44 45 render: function () { 46 c.save(); 47 c.translate(xmiddle, ymiddle); 48 c.rotate(this.angle * radians); 49 c.fillStyle = "hsla("+ this.color +", 100%, 50%, "+ this.alpha +")"; 50 c.beginPath(); 51 c.arc(this.x, this.y, this.size, 0, Math.PI * 2, true); 52 c.fill(); 53 c.restore(); 54 } 55 }; 56 57 function randomRange(min,max){ 58 return Math.random()*(max-min) + min; 59 } 60 61 function init() { 62 var particles = [], 63 max = 20, 64 randomx = Math.floor(randomRange(0, canvas.width)), 65 randomy = Math.floor(randomRange(0, canvas.height)); 66 67 body.appendChild(canvas); 68 canvas.width = win.innerWidth; 69 canvas.height = win.innerHeight; 70 71 while(max-- > 0) { 72 particles.push(new Particle(Math.floor(randomRange(0, canvas.width)), 73 Math.floor(randomRange(0, canvas.height)))); 74 } 75 76 setInterval(function () { 77 var count = 0, 78 len = particles.length, 79 particle; 80 81 c.save(); 82 c.fillStyle = "hsla(0, 0%, 0%, 0.02)"; 83 c.fillRect(0, 0, canvas.width, canvas.height); 84 c.restore(); 85 86 for (count; count < len; count++) { 87 particle = particles[count]; 88 89 particle.update(); 90 particle.render(); 91 } 92 }, 1000/30); 93 } 94 95 init(); 96 97}) (window, document);