Javascript 如何使用JS使画布粒子跟随鼠标?

Javascript 如何使用JS使画布粒子跟随鼠标?,javascript,html,canvas,Javascript,Html,Canvas,我想让粒子跟随鼠标,但我不确定如何做到这一点 我想我可以用鼠标的位置来代替x和y,但我也能找到答案 请给我一个几乎准确的答案,不要举例 window.onload=function(){ var canvas=document.createElement(“画布”), c=canvas.getContext(“2d”), 粒子={} particleIndex=0, particleNum=Math.random()*2; 画布宽度=400; 画布高度=400; document.body.a

我想让粒子跟随鼠标,但我不确定如何做到这一点

我想我可以用鼠标的位置来代替x和y,但我也能找到答案

请给我一个几乎准确的答案,不要举例

window.onload=function(){
var canvas=document.createElement(“画布”),
c=canvas.getContext(“2d”),
粒子={}
particleIndex=0,
particleNum=Math.random()*2;
画布宽度=400;
画布高度=400;
document.body.appendChild(画布);
c、 fillStyle=“黑色”;
c、 fillRect(0,0,canvas.width,canvas.height);
函数粒子(){
这个.x=canvas.width/10;
这个.y=canvas.height/2;
this.vx=Math.random()*10-5;
this.vy=Math.random()*10-5;
这个重力=0.2;
particleIndex++;
粒子[particleIndex]=这个;
this.id=particleIndex;
这就是生命=0;
this.maxLife=Math.random()*30+10;
this.color=“rgb(“+parseInt(Math.random()*255,10)+”,0,0)”;
this.color2=“hsl(“+parseInt(Math.random()*255,10)+”,50%,50%)”;
}
Particle.prototype.draw=函数(){
this.x+=this.vx;
this.y+=this.vy;
if(Math.random()<0.1){
this.vx=Math.random()*10-5;
this.vy=Math.random()*10-5;
}
this.vy+=this.gravity;
这就是生活;
如果(this.Life>=this.maxLife){
删除粒子[this.id];
}
c、 fillStyle=this.color2;
c、 fillRect(this.x,this.y,10,10);
};
//var p=新粒子();
setInterval(函数(){
c、 fillStyle=“rgba(0,0,0,0.5)”;
c、 fillRect(0,0,canvas.width,canvas.height);
用于(粒子中的var i){
粒子[i].draw();
}
对于(var i=0;i};这里有一个演示如何击退鼠标上的粒子并恢复鼠标上的粒子。您可以修改该代码来进行“跟随鼠标”设计。不过我希望它跟随鼠标的位置。明白,您希望吸引粒子而不是排斥粒子。文章显示了当粒子位于鼠标位置的影响半径范围内时如何进行排斥。吸引的过程是一样的,只是相反而已好了,我开始明白了。我必须单击鼠标才能找到鼠标位置吗?因为我希望它在页面加载时自动跟随鼠标。很抱歉,我不太明白这一点。当然。:-)您可以在mousemove而不是mousedown上触发重新对齐。是的,您必须使用传递到mousemove处理程序中的事件对象来跟踪鼠标位置。现在已经过了午夜了,所以我今晚太累了,不能做演示了,但是试试看,明天我会再看这个问答。晚安!