class DrawCanvas { constructor() { this._ctx = null this._canvas = null this._executionArr = [] this._pathArr = [] this._style = null } _init({ width, height, canvas, dicTypePath = '' }) { if (!width || !height || !canvas) return const ctx = canvas.getContext('2d') const dpr = wx.getSystemInfoSync().pixelRatio canvas.width = width * dpr canvas.height = height * dpr ctx.scale(dpr, dpr) this._canvas = canvas this._ctx = ctx this._executionArr = [] //每移动一笔的数据 this._pathArr = [] //抬起落下为一笔 if (dicTypePath) { // 添加路径底图 const path = this.sPath2cPath(dicTypePath) this._ctx.stroke(path) this._ctx.clip(path) } } mouseStart() { this._executionArr = [] } mouseMove({ x = 0, y = 0 }) { if (!this._style) return this._executionArr.push([x, y]) this._ctx.fillStyle = this._style this._ctx.fillRect(x - 5, y - 5, 10, 10) console.log('画图并存储'); } mouseEnd() { this._pathArr.push({ fillStyle: this._style, path: this._executionArr }) } mouseBack() { // 删除每个移动数据 if (this._pathArr.length) { // 清空画布 this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height) 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.fillStyle this._ctx.fillRect(es[0] - 5, es[1] - 5, 10, 10) } } } } // 切换画笔 changeBrush(url = '') { if (!url) return const img = this._canvas.createImage() img.onload = () => { this._style = this._ctx.createPattern(img, 'repeat') } img.src = url } // svg 路径转 canvas 路径 sPath2cPath(path = '') { if (!path || !this._canvas) return const arr = path.split(/(^|\s+)(?=[A-Z])/).filter(el => el !== ' ') const PATH = this._canvas.createPath2D(); for (let k = 0; k < arr.length; k++) { const el = arr[k].replace(/\s+/g, ','); const key = el.replace(/[^A-Z]/g, '') const value = el.replace(/[A-Z]/g, '').split(',') if (key === 'M') { PATH.moveTo(value[0], value[1]); } else if (key === 'C') { PATH.bezierCurveTo(value[0], value[1], value[2], value[3], value[4], value[5]); } else if (key === 'L') { PATH.lineTo(value[0], value[1]); } } return PATH } // 清除画布 clear() { // 清空画布 this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height) // this._ctx.globalCompositeOperation = "source-over" //覆盖 // 清除路径数据 this._pathArr = [] this._executionArr = [] } // 销毁 destory() { this._ctx = null this._canvas = null this._executionArr = [] this._pathArr = [] this._style = null } // 保存 save() { wx.canvasToTempFilePath({ canvas: this._canvas, success(res) { console.log('保存', res.tempFilePath); } }) } } export { DrawCanvas }