Browse Source

增加背景色,优化代码

caner 1 year ago
parent
commit
e9ea968a15
1 changed files with 20 additions and 9 deletions
  1. 20 9
      index/drawCanvas.js

+ 20 - 9
index/drawCanvas.js

@@ -7,6 +7,7 @@ class DrawCanvas {
     this._pathArr = [] //抬起落下为一笔
     this._style = null
     this._matrix = null
+    this._path = null
   }
 
   _init({ width, height, canvas, dicTypePath = '', callBack }) {
@@ -19,11 +20,15 @@ class DrawCanvas {
     this._matrix = ctx.getTransform() //IOS真机矩阵没有返回完整参数,导致无法旋转
     this._executionArr = []
     this._pathArr = []
+    // 加个背景
+    this._ctx.fillStyle = "#FFFFFF";
+    this._ctx.fillRect(0, 0, width, height);
     // 添加路径底图 
     const path = this.sPath2cPath(dicTypePath)
     if (path) {
       this._ctx.stroke(path)
-      // this._ctx.clip(path) //IOS真机裁切后,导致无法画图
+      this._ctx.clip(path) //IOS真机裁切后,导致无法画图
+      this._path = path
     }
     callBack()
     console.log('初始化完成');
@@ -35,7 +40,6 @@ class DrawCanvas {
   }
 
   mouseMove({ x = 0, y = 0 }) {
-    if (!this._style || !this._style.fillStyle) return
     console.log('移动中');
     this._executionArr.push([x, y])
     this._ctx.fillStyle = this._style.fillStyle
@@ -45,10 +49,9 @@ class DrawCanvas {
   }
 
   mouseEnd() {
-    if (!this._style || !this._style.fillStyle) return
-    console.log('移动结束');
+    if (!this._style) return
     this._pathArr.push({
-      fillStyle: this._style,
+      ...this._style,
       path: this._executionArr
     })
   }
@@ -58,16 +61,19 @@ class DrawCanvas {
     if (!this._pathArr.length || !this._ctx) return
     // 清空画布
     this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height)
+    this._ctx.fillStyle = "#FFFFFF";
+    this._ctx.fillRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height);
+    if (this._path) this._ctx.stroke(this._path)
     this._pathArr.pop()
     // 重画
     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.style.fillStyle
-        const X = es[0] - (el.style.w / 2)
-        const Y = es[1] - (el.style.h / 2)
-        this._ctx.fillRect(X, Y, el.style.w, el.style.h)
+        this._ctx.fillStyle = el.fillStyle
+        const X = es[0] - (el.w / 2)
+        const Y = es[1] - (el.h / 2)
+        this._ctx.fillRect(X, Y, el.w, el.h)
       }
     }
   }
@@ -114,6 +120,10 @@ class DrawCanvas {
     if (!this._ctx) return
     // 清空画布
     this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height)
+    // 画上背景
+    this._ctx.fillStyle = "#FFFFFF";
+    this._ctx.fillRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height);
+    if (this._path) this._ctx.stroke(this._path)
     // 清除路径数据
     this._pathArr = []
     this._executionArr = []
@@ -127,6 +137,7 @@ class DrawCanvas {
     this._pathArr = []
     this._style = null
     this._matrix = null
+    this._path = null
   }
 
   // 保存