我有这段 javascript 代码,当我点击按钮时, Canvas 会被清除。
但是当我移动鼠标时, Canvas 会显示我之前写的内容,而且它不会以空白 Canvas 开始
单击按钮后如何从空白 Canvas 开始?
谢谢。
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<div id="buttons">
<input type="button" id="clear" value="Clear">
<input type="button" onClick="erase()" value="Erase">
</div>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove',
function(evt){
var mousePos = getMousePos(canvas, evt);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = 'red';
ctx.lineTo(mousePos.x,mousePos.y);
ctx.stroke();
}
);
document.getElementById('clear').addEventListener('click', function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}, false);
function erase(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
</script>
</body>
</html>
最佳答案
请记住使用 beginPath()
清除在使用 clearRect()
后仍然存在的路径,例如:
function(evt){
var mousePos = getMousePos(canvas, evt);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = 'red';
ctx.beginPath(); // <- here
//ctx.moveTo(x, y); // you will probably also want this at some point
ctx.lineTo(mousePos.x,mousePos.y);
ctx.stroke();
}
关于javascript - 带按钮的 HTML5 干净 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42742538/