【发布时间】:2014-01-02 07:15:34
【问题描述】:
此刻画布创建了 15 个以不同速度移动的三角形。当其中一个离开画布窗口时:
if(p.x >= W){
p.x = -300;
//Set new y coordinates
}
之后它从头开始,所以它是一个循环。问题是,三角形从它在开始时设置的相同 y 坐标开始。如何说三角形离开窗口时应该有新的 y 坐标?
window.onload = function () {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var W = canvas.width = window.innerWidth;
var H = canvas.height = window.innerHeight;
var r = Math.floor(Math.random()*20);
reqAnimFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var mp = 15; //max particles
var particles = [];
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()*(mp - 1) + 1) //density
})
console.log("again");
}
function animate() {
reqAnimFrame(animate);
for(var i = 0; i < mp; i++)
{
var p = particles[i];
p.x += p.d;
if(p.x >= W){
p.x = -300;
//Give the triangle new y coordinates
}
draw();
}
}
function draw() {
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = "rgba(0,204,142,1";
ctx.beginPath();
for(var i = 0; i < mp; i++)
{
var p = particles[i];
ctx.moveTo(p.x,p.y);
ctx.lineTo(p.x + 150, p.y + (-180));
ctx.lineTo(p.x + 300, p.y);
}
ctx.fill();
}
animate();
};//onload function
【问题讨论】:
标签: javascript html animation canvas random