Javascript 圆圈跟随鼠标HTML5画布jQuery

Javascript 圆圈跟随鼠标HTML5画布jQuery,javascript,html,html5-canvas,Javascript,Html,Html5 Canvas,我试图在HTML画布上画一个圆圈,跟随我在游戏中使用的鼠标。我试图使圆在每次迭代中移动5px,但它在水平方向移动时会变慢,在垂直方向移动时会变快。以下是我使用的数学: x=distance between mouse and circle on the x-axis y=distance between mouse and circle on the y-axis z=shortest distance between mouse and circle a=number of units cir

我试图在HTML画布上画一个圆圈,跟随我在游戏中使用的鼠标。我试图使圆在每次迭代中移动5px,但它在水平方向移动时会变慢,在垂直方向移动时会变快。以下是我使用的数学:

x=distance between mouse and circle on the x-axis
y=distance between mouse and circle on the y-axis
z=shortest distance between mouse and circle
a=number of units circle should move along the x-axis
b=number of units circle should move along the y axis


x^2 + y^2=z^2
Want the total distance traveled every iteration to be five pixels
a^2 + b^2 = 25
b/a=y/x
b=ay/x
a=sqrt(25-ay/x^2)
a^2+ay/x-25=0
Use Quadratic formula to find both answers
a=(-y/x+-sqrt(y/x)^2+100)/2
我在下面的代码中复制了这个问题

$(函数(){
让画布=$(“画布”)[0];
设ctx=canvas.getContext(“2d”);
//获取鼠标的位置,并将值存储在变量mouseX和mouseY中
设mouseX=mouseY=0;
$(“画布”).mousemove(函数(e){
mouseX=e.pageX;
mouseY=e.pageY;
}).触发器(“鼠标移动”);
设circleX=0;
设circleY=0;
函数循环(t){
//背景
ctx.fillStyle=“蓝色”;
ctx.fillRect(0,0,canvas.width,canvas.height);
设xFromMouse=mouseX-circleX;
设yFromMouse=mouseY-circleY;
设yxRatio=yFromMouse/xFromMouse;
设xyRatio=xFromMouse/yFromMouse;
让速度=25;
设possibleXValues=[(-yxRatio+Math.sqrt(Math.pow(yxRatio,2)+(4*速度)))/2,(-yxRatio-Math.sqrt(Math.pow(yxRatio,2)+(4*速度))/2];
//我使用此代码作为临时修复,以防止圆完全消失
如果(xFromMouse==0 | | isNaN(yxRatio)| | isNaN(可能值[0])| | isNaN(可能值[1])){
可能值=[0,0];
比值=0;
}
//使用b=ay/x计算y值
设possibleYValues=[possibleXValues[0]*yxRatio,possibleXValues[1]*yxRatio];
如果(xFromMouse>=0){
circleX+=possibleXValues[0];
circleY+=可能值[0];
}否则{
circleX+=可能的ExValues[1];
circleY+=可能值[1];
}
ctx.beginPath();
ctx.arc(circleX,circleY,25,0,2*Math.PI,false);
ctx.fillStyle=“红色”;
ctx.lineWidth=0;
ctx.fill();
window.requestAnimationFrame(循环);
}
window.requestAnimationFrame(循环);
});

我认为使用笛卡尔坐标到极坐标的转换可能会更好。这里有一个我以前做过的例子。这将允许您在每次迭代“速度”中有一个一致的步骤

//画布、上下文、鼠标。
设c,a,m={x:0,y:0};
//装载。
window.onload=函数(){
设圆={},
w、 h,,
速度=5;//步进速度=5“像素”(这在任何一个方向上都是分数,具体取决于行驶方向)。
//设置
c=document.getElementById('canvas');
a=c.getContext('2d');
w=c.width=window.innerWidth;
h=c.高度=窗内高度;
函数move(){
//获取鼠标到圆的距离和角度。
设v1m=circle.x-m.x,
v2m=圆y-m.y,
vDm=Math.sqrt(v1m*v1m+v2m*v2m),
vAm=数学atan2(v2m,v1m);
//如果距离高于某个阈值,要停止抖动,请以“速度”将圆圈移向鼠标。
如果(vDm>速度){
圆x-=数学cos(vAm)*速度;
圆y-=数学正弦(vAm)*速度;
}
}
函数绘图(){
//全部画出来。
a、 fillStyle=“蓝色”;
a、 fillRect(0,0,w,h);
a、 fillStyle=“红色”;
a、 beginPath();
a、 圆弧(圆.x,圆.y,圆.r,数学PI*2,假);
a、 closePath();
a、 填充();
}
圆={x:w/2,y:h/2,r:25};
函数animate(){
请求动画帧(动画);
move();
draw();
}
c、 onmousemove=函数(e){
m、 x=e.pageX;
m、 y=e.pageY;
};
制作动画();
}