こんにちは。きんくまです。
JavaScriptを勉強中なんで、パーティクルを作成してみました。
Flashのインタラクティブな部分がJSによってどのくらい置き換わっていくのか興味があります。
画面をクリックすると、四角いパーティクルがとぶようになっています。
タイマーでFPSを60に設定してあります。
各ブラウザで実行速度を比較してみたところ面白かったので、観察メモを書きます。
■IE7
実行速度が遅い。だけど、ガベコレでガクっとなることがない。
■Firefox3
実行速度がIEより全然速い。だけど、Choromeより遅い気がする。ガベコレでときどきガクっとなって止まることがある。
■Chorome
一番実行速度が速い。ガベコレもなくて一番スムーズ。
ただ、今回のソースの作り方やjQueryとの相性の問題もあると思うので、ブラウザそのものの性能というわけではないと思います。
今回のソース(JavaScript部分)を載せます。
jQueryを使っています。
たぶんJavaScriptネイティブコードでやるともっともっと速くなると思います。
※修正 一回クリックで1つのパーティクルは地味すぎるのでいろいろと修正。
下のソースコードからちょびっと本番ではかえてます。
//Perticle
var Perticle = function(x, y) {
this.vx = Math.random() * 5 * (Math.random() * 2 < 1 ? 1 : -1) + 1;
this.vy = -Math.random() * 20;
this.width = Math.floor(Math.random() * 15) + 5;
this.x = x - this.width / 2;
this.y = y - this.width / 2;
this.id = "ptc" + Perticle.initID;
Perticle.initID++;
};
Perticle.initID = 1;
Perticle.prototype = {
update: function() {
this.vy += 0.2;
this.x += this.vx
this.y += this.vy;
var thisObj = $('#' + this.id);
if (this.y - this.width > Base.height) {
Perticles.remove(this.id);
thisObj.remove();
} else {
thisObj.css({
top: Math.floor(this.y),
left: Math.floor(this.x)
});
}
},
src: function() {
var s = '<div id="' + this.id + '"></div>';
return s;
},
setStyle: function() {
var r = Math.floor(Math.random() * 0xff * 2 / 5 + 0xff * 3 / 5).toString(16);
var g = Math.floor(Math.random() * 0xff * 4 / 5 + 0xff * 1 / 5).toString(16);
var b = Math.floor(Math.random() * 0xff * 3 / 5 + 0xff * 2 / 5).toString(16);
var color = '#' + r + g + b;
$('#' + this.id).css({
height: this.width + 'px',
width: this.width + 'px',
background: color,
position: 'absolute',
top: Math.floor(this.y),
left: Math.floor(this.x)
});
}
}
//Perticles
var Perticles = function() { };
Perticles.data = {};
Perticles.add = function(perticle) {
Perticles.data[perticle.id] = perticle;
}
Perticles.remove = function(perticleID) {
delete Perticles.data[perticleID];
}
//Enterframe
var Enterframe = function() {}
Enterframe.timer = null;
Enterframe.start = function() {
clearInterval(Enterframe.timer);
var fps = Math.floor(1000 / 60);
Enterframe.timer = setInterval(Enterframe.update, fps);
}
Enterframe.update = function() {
for (var perticle in Perticles.data) {
Perticles.data[perticle].update();
}
}
//Base
var Base = function() { }
Base.height = 0;
Base.prototype = {
update: function() {
Base.height = $('body').height();
}
}
//init
$(function() {
Enterframe.start();
Perticles.add(new Base());
var wrap = $('#wrap');
wrap.bind('click', function(e) {
var p;
for (var i = 0; i < 5; i++) {
p = new Perticle(e.clientX, e.clientY);
wrap.append(p.src());
p.setStyle();
Perticles.add(p);
}
});
});
