以下代码在按钮上单击
清除画布context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears
但是,当我尝试重绘它时,出现了我不想要的旧图形。我想开始在新的空白画布上画画
我如何实现这一目标?
如果您希望查看整个代码..
$(function () {
var c = document.getElementById("canvas");
var context = c.getContext("2d");
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
$('#canvas').mousedown(function (e) {
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').mousemove(function (e) {
if (paint) {
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvas').mouseup(function (e) {
paint = false;
});
$('#canvas').mouseleave(function (e) {
paint = false;
});
$('#clear').click(function (e) {
e.stopPropagation();
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears
});
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
function redraw() {
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
context.strokeStyle = "#000000";
context.lineJoin = "round";
context.lineWidth = 2;
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();
}
}
});
答案 0 :(得分:0)
您必须清除以下数组clickX
,clickY
和clickDrag
:
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
clickX = []; // clear mouse "logs"
clickY = [];
clickDrag = [];
<强> Working jsFiddle 强>
当您单击或拖动鼠标时,将调用addClick
方法,该方法使用鼠标坐标填充数组clickX
,clickY
和clickDrag
。调用redraw
方法时,它会在画布上再次绘制点。因此清除这些阵列将解决您的问题。