当您单击代码笔上的“清除画布”按钮时,将显示好像已清除画布,但是如果您再次尝试绘图,则所有旧行将重新出现。
//Redraw
function redraw(){
$("#clearcanvas").click(function () {
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
});
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 5;
for(var i=0; i < clickX.length; i++) {
context.beginPath();
if(clickDrag[i] && i){
context.moveTo(clickX[i-1], clickY[i-1]);
}
else {
context.moveTo(clickX[i]-1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
}
完整代码:http://codepen.io/urketadic/pen/AXGKvp
最佳答案
因为您将每个绘制的线的信息存储在clickX
,clickY
和clickDrag
数组中。即使清除了画布,画布也将绘制每条线。您将要清空这些数组项:
$("#clearcanvas").click(function () {
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
clickX = []; clickY = []; clickDrag = []; // or 'new Array()' or '.length = 0'
});