现在我写了一个实时指向鼠标的箭头,现在想让它移动向鼠标位置,请问如何实现

u010313216 2015-04-20 02:13:54
指向鼠标箭头代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>箭头</title>
</head>
<body>
<canvas width="1000" height="800" id="canvas"></canvas>
<script>
function Arrow(canvas){
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.x = 250;
this.y = 200;
this.rotation = 0;
this.lastRotation = 0;
Arrow.prototype.drawArrow = function(rotation){
//this.ctx.clearRect(0,0,500,500);
this.ctx.rotate(-this.lastRotation);
this.ctx.rotate(rotation);
this.ctx.beginPath();
this.ctx.moveTo(-50,-25);
this.ctx.lineTo(0,-25);
this.ctx.lineTo(0,-50);
this.ctx.lineTo(50,0);
this.ctx.lineTo(0,50);
this.ctx.lineTo(0,25);
this.ctx.lineTo(-50,25);
this.ctx.lineTo(-50,-25);
this.ctx.closePath();
this.ctx.stroke();
this.lastRotation = rotation;
}
}

function RotateToMouse(canvas){
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.arrow;
this.ctx.translate(250,200);
this.mouseX = 0;
this.mouseY = 0;
RotateToMouse.prototype.init = function(){
this.arrow = new Arrow(canvas);
this.arrow.drawArrow();

var self = this;
canvas.addEventListener("mousemove",function(e){
return self.getMousePosition(e);
});
};

RotateToMouse.prototype.getMousePosition = function(event){
event = event || window.event;
if(event.pageX || event.pageY){
this.mouseX = event.pageX;
this.mouseY = event.pageY;
}else{
this.mouseX = event.clientX + document.body.scrollLeft - document.body.clientLeft;
this.mouseY = event.clientY + document.body.scrollTop - document.body.clientTop;
}
this.arrow.rotation = Math.atan2(this.mouseY - this.arrow.y, this.mouseX - this.arrow.x);
this.ctx.clearRect(-750,-600,1000,800);
this.arrow.drawArrow(this.arrow.rotation);
};
this.init();
}
var canvas = document.getElementById('canvas');
new RotateToMouse(canvas);
</script>
</body>
</html>


让箭头可以向鼠标位置移动,如何实现?谢谢
...全文
94 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧