编写一个简单的脚本来拥有两个按钮。一个按钮动画一个"绘画"功能,其中矩形跟随画布周围的光标。另一个按钮会在画布后面显示一个矩形,但不会像另一个那样留下痕迹。我有链接按钮来做不同的功能。现在,跟随按钮不起作用,它确实清除了画布,但它仍然允许你画画。看到跟随按钮后,看起来paint功能仍在运行。任何帮助表示赞赏。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
</head>
<body>
<input type="button" value="Paint" onclick="isPaint()">
<input type="button" value="Follow" onclick="isFollow()">
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
function isPaint(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//change draw color
ctx.fillStyle = "#FF0000";
ctx.clearRect(0,0,500,500);
canvas.addEventListener("mousemove", function(event) {
ctx.fillRect(event.x,event.y,10,10);
})
}
function isFollow(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//change draw color
ctx.fillStyle = "#FF0000";
ctx.clearRect(0,0,500,500);
}
</script>
</body>
</html>
答案 0 :(得分:1)
为我工作:http://jsfiddle.net/XF7m4/1/
使用document.getElementById("paint").onclick= function (){
PS:并考虑删除mousemouse监听器;)
答案 1 :(得分:1)
要实现您的目标,您需要更多地增强代码。
主要想法是仅将mousemove
事件绑定一次并清除画布,如果它的行为类似于follow
。
尝试使用以下代码:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas</title>
</head>
<body>
<input type="button" value="Paint" onclick="CanvasPainter.paint()" />
<input type="button" value="Follow" onclick="CanvasPainter.follow()" />
<canvas id="myCanvas" width="500" height="500"></canvas>
<script type="text/javascript">
(function () {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//change draw color
ctx.fillStyle = "#FF0000";
var CanvasPainter = {
isPaint: false,
isFollow: false,
paint: function () {
this.isPaint = true;
this.isFollow = false;
return;
},
follow: function () {
this.isPaint = false;
this.isFollow = true;
return;
}
};
window.CanvasPainter = CanvasPainter;
canvas.addEventListener("mousemove", function (event) {
if (CanvasPainter.isPaint || CanvasPainter.isFollow) {
if (CanvasPainter.isFollow) {
// Clear canvas on every mousemove if it is a follow
ctx.clearRect(0, 0, 500, 500);
}
ctx.fillRect(event.x, event.y, 10, 10);
}
return;
});
return;
})();
</script>
</body>
</html>
希望这有帮助!
答案 2 :(得分:0)
你的isPaint()函数正在为&#34; mousemove&#34;添加一个事件监听器。到画布,但它没有被删除在isFollow()函数中。如果你在isFollow()函数中删除你的监听器,这应该可以解决你的问题。