【发布时间】:2014-01-02 23:36:48
【问题描述】:
由于我添加了o: Math.random()*(1 - 0.1) + 0.1 //opacity 用于随机不透明度值,因此动画无法流畅运行。我能做些什么来防止这种情况发生?如何使我的脚本更有效地提高性能?
window.onload = function () {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var W = canvas.width = window.innerWidth;
var H = 550;
var mp = 45; //max particles
var particles = [];
//var rotate = 180;
reqAnimFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
for ( var i = 0; i < mp; i++ )
{
particles.push({
x: Math.floor(Math.random()*W), //x-coordinate
y: Math.floor(Math.random()*H), //y-coordinate
d: Math.floor(Math.random()*(12 - 1) + 1), //density
r: Math.floor(Math.random()*(70 - 10) + 10), //radius
o: Math.random()*(1 - 0.1) + 0.1 //opacity
})
}
function animate() {
reqAnimFrame(animate);
for ( var i = 0; i < mp; i++ )
{
var p = particles[i];
p.x += p.d;
if(p.x >= W + p.r){
p.x = -300;
p.y = Math.floor(Math.random()*H);
}
draw();
}
}
function draw() {
ctx.clearRect(0, 0, W, H);
for ( var i = 0; i < mp; i++ )
{
var p = particles[i];
ctx.fillStyle = "rgba(51,51,51," + p.o + ")";
ctx.beginPath();
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, false);
ctx.fill();
//ctx.moveTo(p.x,p.y);
//ctx.lineTo(p.x + 150, p.y + (-180));
//ctx.lineTo(p.x + 300, p.y);
}
}
animate();
};//onload function
【问题讨论】:
标签: javascript html animation canvas