我正在尝试使用mousemove
事件创建一个圆圈移动动画,每次圆圈将从屏幕上的mouse.x
和mouse.y
坐标移动。所以我声明我的mouse
坐标对象和drawCricle
对象构造函数:
var mouse = {
x:canvas.width/2,
y:canvas.height/2
}
function Circle (x,y,r,dy){
this.x = x;
this.y = y;
this.r = r;
this.dy = dy;
this.update = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,Math.PI*2);
ctx.fillStyle = 'blue';
ctx.fill();
this.y+=this.dy;
if(this.y<this.r || this.y+this.r>canvas.height){
this.dy=-this.dy;
}
}
}
在我添加mousemove
事件后,我想我可以通过我的mouvemove eventListenter
分配鼠标x / y坐标:
var myCircle = new Circle(mouse.x,mouse.y,30,2);
function animate(){
ctx.clearRect(0,0,canvas.width,canvas.height);
myCircle.update();
requestAnimationFrame(animate);
}
window.addEventListener("mousemove",function(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
animate();
});
问题是mouse.x
和mouse.y
值不会从原始canvas.width/2
值更改,因此我尝试将animation()
函数包装在{window.addEventListener
内1}}而只是在其中调用它,就像:
window.addEventListener("mousemove",function(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
var myCircle = new Circle(mouse.x,mouse.y,30,2);
function animate(){
ctx.clearRect(0,0,canvas.width,canvas.height);
myCircle.update();
requestAnimationFrame(animate);
}
animate();
});
这可能会有点工作,但它看起来真的很愚蠢,并使我的浏览器出现巨大的滞后峰值,有没有其他方法可以做到这一点?
答案 0 :(得分:1)
调用update
函数时,您还需要传递鼠标坐标...
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var mouse = {
x: canvas.width / 2,
y: canvas.height / 2
};
function Circle(x, y, r, dy) {
this.r = r;
this.dy = dy;
this.update = function(x, y) {
ctx.beginPath();
ctx.arc(x, y, this.r, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
this.y += this.dy;
if (this.y < this.r || this.y + this.r > canvas.height) {
this.dy = -this.dy;
}
};
}
var myCircle = new Circle(mouse.x, mouse.y, 30, 2);
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
myCircle.update(mouse.x, mouse.y);
requestAnimationFrame(animate);
}
canvas.addEventListener("mousemove", function(e) {
mouse.x = e.offsetX;
mouse.y = e.offsetY;
});
animate();
body{margin:10px 0 0 0;overflow:hidden}canvas{border:1px solid #e4e6e8}
<canvas id="canvas" width="635" height="208"></canvas>