マウスから火花が飛び出すアニメーションです。
作り方が公開されていましたので試してみました。
JavaScript
var SCREEN_HEIGHT = window.innerHeight; // 画面の高さ
var GRAVITY = 0.4; // 重力係数
// 変数
var ctx; // 2Dコンテキスト
var particlelist = []; // 作成したパーティクルを入れる配列
var mx = null; // マウスのx座標
var my = null; // マウスのy座標
// コンストラクト
var Particle = function(x,y){
this.x = x;
this.y = y;
this.vx = 0; // x軸方向の速度
this.vy = 0; // y軸方向の速度
this.radius = 0; // 半径
this.color = null; // 色
this.isRemove = false; // 消去フラグ
}
// メソッド
// 初速度、サイズ、色をランダムに設定
Particle.prototype.create = function(){
this.vx = Math.random() * 6 - 3;
this.vy = Math.random() * (-6) - 2;
this.radius = Math.random() * 20 + 5;
var r = 150;
var g = Math.floor(Math.random() * 100 + 155);
var b = Math.floor(Math.random() * 155 + 100);
this.color = "rgb(" + r + "," + g + "," + b + ")";
}
// 位置を更新
Particle.prototype.update = function(){
this.vy += GRAVITY;
this.x += this.vx;
this.y += this.vy;
this.radius *= 0.97;
// パーティクルが画面の外に出たとき削除フラグを立てる
if(this.x < 0 || this.x > SCREEN_WIDTH || this.y > SCREEN_HEIGHT){
this.isRemove = true;
}
}
// 描画
Particle.prototype.draw = function(){
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,false);
ctx.fill();
}
// 初期設定
window.onload = function(){
var canvas = document.querySelector('#mycanvas');
// canvas要素の存在をチェック
if(!canvas || !canvas.getContext){
return false;
}
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
ctx = canvas.getContext("2d");
// canvasにマウスイベントを登録
canvas.addEventListener("mousemove",updateMousePos,false); // マウス移動時イベント
canvas.addEventListener("mouseout",restMousePos,false); // マウス移動が画面外に出た際のイベント
// メインループを実行
loop();
}
// マウスの位置を取得
function updateMousePos(e) {
var rect = e.target.getBoundingClientRect();
mx = e.clientX - rect.left;
my = e.clientY - rect.top;
}
// マウスの位置をリセット
function restMousePos(e) {
mx = null;
my = null;
}
// メインループ
function loop(){
add();
update();
draw();
setTimeout(loop,1000/FPS);
}
// パーティクルの追加
function add(){
if(mx !== null && my !== null){
// インスタンスを生成
var p = new Particle(mx,my);
p.create();
// インスタンスを配列に格納
particlelist.push(p);
}
}
// パーティクルの位置を更新
function update(){
var list = [];
for(var i=0; i<particlelist.length; i++){
particlelist[i].update();
// 削除フラグがたっていなければ配列に格納
if(!particlelist[i].isRemove) {
list.push(particlelist[i]);
}
}
particlelist = list;
}
// パーティクルの描画
function draw(){
// 背景を描画
ctx.fillStyle = "rgb(0,0,0)";
ctx.fillRect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
// パーティクルを描画
ctx.save();
ctx.globalCompositeOperation = "lighter";
for(var i=0; i<particlelist.length; i++){
particlelist[i].draw();
}
ctx.restore();
}
HTML
<style type="text/css">
#mycanvas {
width:100%;
height:100%;
margin:0;
background-color:#000;
}
</style>
</head>
<body>
<p>マウスからパーティクルが飛び出すアニメーション</p>
<canvas id="mycanvas">
</canvas>
</body>
サンプル