パーティクルオブジェクトを作成して動かす

基本的な作りは下記記事をベースに作成します。

HTML5で作るCanvasアニメーションの基礎

上記の記事では一つの円を動かすだけだったので描画関数だけ作成しました。

function drawCircle(x, y, scale, color) {
ctx.beginPath();
ctx.arc(x, y, scale, 0, 2*Math.PI, false);
ctx.fillStyle = color;
ctx.fill();
}

パーティクルの場合、粒子一つ一つに位置情報や速度の設定をしたいので、少し拡張してオブジェクトとして作成します。

var Particle = function(scale, color, speed) {
this.scale = scale; //大きさ
this.color = color; //色
this.speed = speed; //速度
this.position = { //位置
x: 100,
y: 100
};
};
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();
};

おさらいもかねて作成したPaticleを使用して描画&移動アニメーションを作成してます。

var canvas = document.querySelector('#canvas-container');
var ctx = canvas.getContext('2d');
var patricle = new Particle(6, '#D0A000', 2);
loop();
function loop() {
requestAnimFrame(loop);
// 描画をクリアー
ctx.clearRect(0,0, canvas.width, canvas.height);
patricle.position.x += patricle.speed;
patricle.draw();
// 画面外に出たら左へ戻る
if (patricle.position.x > canvas.width) patricle.position.x = -30;
}

オブジェクトを量産してパーティクルっぽくする

パーティクルをたくさん並べたいのですが、位置はランダムで配置したいですね。
JavaScriptでランダムな数値を取得するには「Math.random()」を使用します。
0~100までのランダムな数値にしたい場合は次のように記述します。

Math.random()*100

2~4など範囲を決める場合は次のようになります。

Math.random() * (4-2) + 2

これをふまえて位置と速度にランダムな数値を指定してみます。

var density = 100; //パーティクルの密度
var particles = []; //パーティクルをまとめる配列
for (var i=0; i<density; i++) {
particles[i] = new Particle(6, '#D0A000', Math.random()*(4-2)+2);
particles[i].position.x = Math.random()*canvas.width;
particles[i].position.y = Math.random()*canvas.height;
particles[i].draw();
}

あとはループ関数ですね。
これはほぼそのままforで囲むだけです。

function loop() {
requestAnimFrame(loop);
// 描画をクリアー
ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height);
for (var i=0; i<density; i++) {
particles[i].position.x += particles[i].speed;
particles[i].draw();
if (particles[i].position.x > canvas.width) particles[i].position.x = -30;
}
}

大きさをランダムにする

小さいものより大きいものを早く移動させた方が立体感が出て良いと思います、大きさによって移動速度も反映されるようにしましょう。

「new Particle」あたりを下記のように変更します。

var scale = ~~(Math.random()*(8-3))+3;
particles[i] = new Particle(scale, '#D0A000', scale/2);

けっこういい感じじゃないですかね。でも奥行き情報を持たないので重なったときにあれなんですけどね。

色をランダムにする

色はあまりランダムすぎてもよくなさそうなのである程度色をピックアップして配列にいれておきます。

var colors = ['#D0A000', '#6DD0A5', '#E084C5'];

あとはnewするときに色の部分に入れてあげればランダムになりますね。

var color = colors[~~(Math.random()*3)];
particles[i] = new Particle(scale, color, scale/2);