JS Canvas メモ
特に意味もないメモ。 何かに使えそう
// 差異の吸収 window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(cb){setTimeout(cb, 17);}; var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var NUM = 10; var particles = []; var W=500,H=500,R=250; canvas.width = W; canvas.height = H; ctx.globalCompositeOperation = "lighter"; for(var i=0;i<NUM;i++){ var positionX = Math.random() * 300; var positionY = Math.random() * 200; var particle = new Particle(ctx,positionX, positionY); particles.push(particle); } function Particle(ctx, x, y){ this.ctx = ctx; this.x = x || 250; this.y = y || 250; this.v = { x: Math.random()*1, y: Math.random()*1 }; this.color = { r: Math.floor(Math.random()*255), g: Math.floor(Math.random()*255), b: Math.floor(Math.random()*255), a: 1 }; } Particle.prototype.render = function(){ this.updatePosition(); this.wrapPosition(); this.draw(); }; Particle.prototype.draw = function(){ ctx = this.ctx; ctx.beginPath(); ctx.fillStyle = this.gradient(); // ctx.rect(this.x,this.y,10,20); ctx.arc(this.x,this.y,R,Math.PI*2,false); ctx.fill(); ctx.closePath(); }; Particle.prototype.updatePosition = function(){ this.x+=this.v.x; this.y+=this.v.y; }; Particle.prototype.wrapPosition = function(){ if(this.x < 0) this.x = W; if(this.x > W) this.x = 0; if(this.y < 0) this.y = H; if(this.y > H) this.y = 0; } Particle.prototype.gradient = function(){ var col = this.color.r + ", " + this.color.g + ", " + this.color.b;; var g = this.ctx.createRadialGradient(this.x,this.y,0,this.x,this.y,R); g.addColorStop(0, "rgba(" + col + ", 1)"); g.addColorStop(0.5, "rgba(" + col + ", 0.2)"); g.addColorStop(1, "rgba(" + col + ", 0)"); return g } function render(){ // 一度図形の消去 ctx.clearRect(0,0,W,H); particles.forEach(function(e){ e.render(); }); // 一定時間置く requestAnimationFrame(render); } render();