uniapp小程序使用canvas对图片批注 实现撤销和恢复上一步代码如何实现
时间: 2023-11-28 21:04:25 浏览: 38
以下是一个简单的示例代码实现在Uniapp小程序中使用canvas对图片进行批注,并实现撤销和恢复上一步操作的功能:
```
<template>
<canvas class="canvas" canvas-id="myCanvas" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas>
</template>
<script>
export default {
data() {
return {
ctx: null, // canvas上下文对象
lastX: 0, // 上一次的x坐标
lastY: 0, // 上一次的y坐标
isDrawing: false, // 是否正在绘制
undoStack: [], // 撤销栈
redoStack: [], // 恢复栈
}
},
onReady() {
// 获取canvas上下文对象
this.ctx = uni.createCanvasContext('myCanvas', this);
this.ctx.drawImage('/static/image/test.png', 0, 0, 300, 300); // 绘制图片
},
touchStart(e) {
this.isDrawing = true;
this.lastX = e.touches[0].x;
this.lastY = e.touches[0].y;
},
touchMove(e) {
if (!this.isDrawing) return;
const currentX = e.touches[0].x;
const currentY = e.touches[0].y;
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(currentX, currentY);
this.ctx.stroke();
this.lastX = currentX;
this.lastY = currentY;
},
touchEnd() {
if (!this.isDrawing) return;
this.isDrawing = false;
// 将当前操作数据存入撤销栈
this.undoStack.push(this.ctx.getImageData(0, 0, 300, 300));
this.redoStack = []; // 清空恢复栈
},
undo() {
if (this.undoStack.length < 1) return;
// 将最后一次操作数据取出来,清空canvas并重新绘制之前的数据
const lastData = this.undoStack.pop();
this.redoStack.push(lastData);
this.ctx.clearRect(0, 0, 300, 300);
this.ctx.putImageData(lastData, 0, 0);
},
redo() {
if (this.redoStack.length < 1) return;
// 将下一步操作数据取出来,重新绘制到canvas上
const nextData = this.redoStack.pop();
this.undoStack.push(nextData);
this.ctx.clearRect(0, 0, 300, 300);
this.ctx.putImageData(nextData, 0, 0);
},
}
</script>
```
在上述代码中,我们定义了一个`undoStack`数组和一个`redoStack`数组来分别存储撤销和恢复栈中的操作数据。在`touchEnd`方法中,每次绘制操作完成后,将当前操作数据存入撤销栈中。在`undo`方法中,我们从撤销栈中取出最后一次操作数据,清空canvas并重新绘制之前的数据,同时将该数据存入恢复栈中。在`redo`方法中,我们从恢复栈中取出下一步操作数据,重新绘制到canvas上,并将该数据存入撤销栈中。