Browse Source

采用重画来进行撤销操作

caner 1 year ago
parent
commit
447bb7e139
1 changed files with 36 additions and 12 deletions
  1. 36 12
      index/drawCanvas.js

+ 36 - 12
index/drawCanvas.js

@@ -6,6 +6,10 @@ class DrawCanvas {
     this._executionArr = []
     this._pathArr = []
     this._style = null
+
+    this.baseMapUrl = null
+    this.baseWidth = null
+    this.baseHeight = null
   }
 
   _init({ width, height, canvas, baseMapUrl = '' }) {
@@ -28,6 +32,9 @@ class DrawCanvas {
     this._ctx = ctx
     this._executionArr = [] //每移动一笔的数据
     this._pathArr = [] //抬起落下为一笔
+    this.baseHeight = height
+    this.baseWidth = width
+    this.baseMapUrl = baseMapUrl
   }
 
   mouseStart() {
@@ -52,12 +59,26 @@ class DrawCanvas {
   mouseBack() {
     // 删除每个移动数据
     if (this._pathArr.length) {
-      const item = this._pathArr.length <= 1 ? this._pathArr[0] : this._pathArr[this._pathArr.length - 1]
-      for (let k = 0; k < item.path.length; k++) {
-        const el = item.path[k];
-        this._ctx.clearRect(el[0] - 5, el[1] - 5, 10, 10)
-      }
+      this._ctx.globalCompositeOperation = "source-over" //覆盖
+      // 清空画布
+      this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height)
       this._pathArr.pop()
+      // 画上底图
+      const img = this._canvas.createImage()
+      img.onload = () => {
+        this._ctx.drawImage(img, 0, 0, this.baseWidth, this.baseHeight)
+        this._ctx.globalCompositeOperation = "source-atop" //画笔重叠部分覆盖
+        // 画上路径
+        for (let k = 0; k < this._pathArr.length; k++) {
+          const el = this._pathArr[k];
+          for (let j = 0; j < el.path.length; j++) {
+            const es = el.path[j];
+            this._ctx.fillStyle = el.fillStyle
+            this._ctx.fillRect(es[0] - 5, es[1] - 5, 10, 10)
+          }
+        }
+      }
+      img.src = this.baseMapUrl
     }
   }
 
@@ -73,14 +94,17 @@ class DrawCanvas {
 
   // 清除画布
   destory() {
-    // this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height)
-    for (let k = 0; k < this._pathArr.length; k++) {
-      const el = this._pathArr[k];
-      for (let j = 0; j < el.path.length; j++) {
-        const es = el.path[j];
-        this._ctx.clearRect(es[0] - 5, es[1] - 5, 10, 10)
-      }
+    // 清空画布
+    this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height)
+    this._ctx.globalCompositeOperation = "source-over" //覆盖
+    // 画上底图
+    const img = this._canvas.createImage()
+    img.onload = () => {
+      this._ctx.drawImage(img, 0, 0, this.baseWidth, this.baseHeight)
+      this._ctx.globalCompositeOperation = "source-atop" //画笔重叠部分覆盖
     }
+    img.src = this.baseMapUrl
+    // 清除路径数据
     this._pathArr = []
     this._executionArr = []
     this._style = null