请问各位帅哥,我想实现中点到鼠标画线,已经用了clearRect了,可是之前画的线还在,为什么?

u010313216 2015-04-08 04:47:35
效果是这样的:
代码是这样的:
<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>

先谢谢各位帅哥了。
...全文
129 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
u010313216 2015-04-08
  • 打赏
  • 举报
回复
还需要closePath,欸。。。 谢谢了。
天际的海浪 2015-04-08
  • 打赏
  • 举报
回复
			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();
			}
暗尘掩月 2015-04-08
  • 打赏
  • 举报
回复

this.ctx.clearRect(0,0,500,400);
this.ctx.beginPath();

87,904

社区成员

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

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