我正在尝试生成一个对象(类似于粒子)并使其遵循特定的路径。我已经创建了一个粒子并让它遵循我想要的路径。我的问题是我无法连续创建遵循相同路径的粒子。
这是我要遵循的路径和代码:
var requestAnimationFrame = window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame
;
var pathArray=[];
pathArray.push({x:490,y:290});
pathArray.push({x:330,y:380});
pathArray.push({x:110,y:300});
//pathArray.push({x:570,y:40});
//pathArray.push({x:570,y:175});
var polypoints = makePolyPoints(pathArray);
var width = 10;
var height = 10;
var position = 0;
var speed = 2;
//var rotation = 0;
//var rotationSpeed = 0.1;
var TimeInterval;
function anim() {
TimeInterval=setTimeout(function () {
requestId=requestAnimationFrame(anim);
// calc new position
position += speed;
if (position > polypoints.length) {
return;
}
var pt = polypoints[position];
//rotation += rotationSpeed;
// draw
ctx2.clearRect(0, 0, layer1.width,layer1.height);
ctx2.save();
ctx2.beginPath();
ctx2.translate(pt.x, pt.y);
//ctx2.rotate(rotation);
ctx2.rect(-width / 2, -height / 2, 10, 10);
ctx2.fill();
ctx2.stroke();
ctx2.restore();
}, 100);
}
function makePolyPoints(pathArray) {
var points = [];
for (var i = 1; i < pathArray.length; i++) {
var startPt = pathArray[i - 1];
var endPt = pathArray[i];
var dx = endPt.x - startPt.x;
var dy = endPt.y - startPt.y;
for (var n = 0; n <= 90; n++) {
var x = startPt.x + dx * n / 90;
var y = startPt.y + dy * n / 90;
points.push({
x: x,
y: y
});
}
}
return (points);
}
以及连续生成粒子的代码:
var packets={};
var packetIndex=0;
var packetNum=5;
ctx.clearRect(0,0,canvas.width,canvas.height);
function packet(){
this.x1=670;
this.y1=350;
this.vx1= Math.random()*5;
//this.vy1=Math.random()*10-5;
packetIndex++;
packets[packetIndex] = this;
this.id = packetIndex;
this.life=0;
this.maxLife=1000;
}
packet.prototype.draw=function(){
this.x1 -=this.vx1;
//this.y +=this.vy;
this.life++;
if(this.life>=this.maxLife){
delete packets[this.id];
}
ctx.fillStyle="black";
ctx.fillRect(this.x1,this.y1,10,10);
};
setInterval(function(){
//ctx.fillStyle="white";
ctx.clearRect(0,0,canvas.width,canvas.height);
for (var i1=0; i1<0.018; i1++){
new packet();
}
for(var i1 in packets){
packets[i1].draw();
}
},40);
};
请给出一个想法,以便我可以将两者结合起来。
提前致谢..