撤消绘图可以通过以下步骤实现:
下面是一个示例代码,演示如何使用JavaScript和HTML5的Canvas制作一个撤消绘图的功能:
<!DOCTYPE html>
<html>
<head>
<title>撤消绘图示例</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var states = []; // 保存绘图状态的栈
function saveState() {
states.push(context.getImageData(0, 0, canvas.width, canvas.height));
}
function restoreState() {
if (states.length > 0) {
context.putImageData(states.pop(), 0, 0);
}
}
function drawCircle(x, y, radius) {
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI);
context.fillStyle = "red";
context.fill();
context.closePath();
}
function clearCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function undo() {
restoreState();
clearCanvas();
redraw();
}
function redraw() {
for (var i = 0; i < states.length; i++) {
context.putImageData(states[i], 0, 0);
}
}
canvas.addEventListener("mousedown", function(event) {
saveState();
var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
drawCircle(x, y, 20);
});
document.addEventListener("keydown", function(event) {
if (event.key === "z" && event.ctrlKey) {
undo();
}
});
</script>
</body>
</html>
以上代码创建了一个画布,当鼠标在画布上点击时,会在点击位置绘制一个红色的圆。按下Ctrl+Z组合键可以撤消上一次绘制的圆。每次绘制圆时,都会保存当前的绘图状态,撤消时将上一次保存的状态恢复并重新绘制。
领取专属 10元无门槛券
手把手带您无忧上云