Canvas Dynamics
by webopixel
HTML
<canvas id="canvas-container" width="600" height="480"></canvas>
CSS
#canvas-container {
width: 600px;
height: 480px;
}
JavaScript
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.querySelector('#canvas-container');
var ctx = canvas.getContext('2d');
var Particle = function(scale, color, vx, vy, gv) {
this.scale = scale; //大きさ
this.color = color; //色
this.vx = vx; //X速度
this.vy = vy; //Y速度
this.gv = gv; //重力
this.position = { // 位置
x: 0,
y: 0
};
};
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.scale, 0, 2*Math.PI, false);
ctx.fillStyle = this.color;
ctx.fill();
};
Particle.prototype.update = function() {
this.vy += this.gv;
this.position.x += this.vx;
this.position.y += this.vy;
// 地面の衝突判定
if (this.position.y > canvas.height - this.scale) {
this.vy *= -0.6;
this.vx *= 0.85;
this.position.y = canvas.height - this.scale;
}
this.draw();
};
var density = 100; //パーティクルの密度
var particles = []; //パーティクルをまとめる配列
var colors = ['#D0A000', '#6DD0A5', '#E084C5'];
for (var i=0; i<density; i++) {
var color = colors[~~(Math.random()*3)];
var scale = ~~(Math.random()*5)+3;
var x = Math.random() * 10 - 5;
var y = Math.random()* 9 + 4;
var g = Math.random()* 0.2 + 0.3;
particles[i] = new Particle(scale, color, x, -y, g);
particles[i].position.x = canvas.width / 2;
particles[i].position.y = 200;
}
loop();
// ループ処理
function loop() {
requestAnimFrame(loop);
// 描画をクリアー
ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height);
for (var i in particles) {
particles[i].update();
}
}