87,904
社区成员
发帖
与我相关
我的任务
分享
<html>
<head>
<title>LineToMouse</title>
</head>
<body>
<canvas id="canvas1" width="500" height="400" style="background:#ffffff"></canvas>
<script>
function LineToMouse(canvas){
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.centerX = 250;
this.centerY = 250;
this.mouseX = 0;
this.mouseY = 0;
LineToMouse.prototype.init = function(){
var self = this;
this.canvas.addEventListener("mousemove",function(e){return self.getMousePosition();});
}
LineToMouse.prototype.getMousePosition = function(e){
e = e || window.event;
this.mouseX = e.clientX;
this.mouseY = e.clientY;
this.drawLine();
}
LineToMouse.prototype.drawLine = function(){
this.ctx.clearRect(0,0,500,400);
this.ctx.moveTo(this.centerX,this.centerY);
this.ctx.lineTo(this.mouseX,this.mouseY);
this.ctx.stroke();
}
this.init();
}
var canvas = document.getElementById("canvas1");
new LineToMouse(canvas);
</script>
</body>
</html>
LineToMouse.prototype.drawLine = function(){
this.ctx.clearRect(0,0,500,400);
this.ctx.beginPath();//重画之前要重置路径
this.ctx.moveTo(this.centerX,this.centerY);
this.ctx.lineTo(this.mouseX,this.mouseY);
this.ctx.stroke();
}
this.ctx.clearRect(0,0,500,400);
this.ctx.beginPath();