|
@@ -0,0 +1,94 @@
|
|
|
|
|
+class DrawCanvas {
|
|
|
|
|
+ constructor() {
|
|
|
|
|
+ this._ctx = null
|
|
|
|
|
+ this._canvas = null
|
|
|
|
|
+ this._executionArr = []
|
|
|
|
|
+ this._pathArr = []
|
|
|
|
|
+ this._style = null
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ _init({ width, height, canvas, baseMapUrl = '' }) {
|
|
|
|
|
+ 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)
|
|
|
|
|
+ // 添加底图
|
|
|
|
|
+ if (baseMapUrl) {
|
|
|
|
|
+ const img = canvas.createImage()
|
|
|
|
|
+ img.onload = () => {
|
|
|
|
|
+ this._ctx.drawImage(img, 0, 0, width, height)
|
|
|
|
|
+ this._ctx.globalCompositeOperation = "source-atop" //画笔重叠部分覆盖
|
|
|
|
|
+ }
|
|
|
|
|
+ img.src = baseMapUrl
|
|
|
|
|
+ }
|
|
|
|
|
+ this._canvas = canvas
|
|
|
|
|
+ this._ctx = ctx
|
|
|
|
|
+ this._executionArr = [] //每移动一笔的数据
|
|
|
|
|
+ this._pathArr = [] //抬起落下为一笔
|
|
|
|
|
+
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ 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) {
|
|
|
|
|
+ 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, 11, 11)
|
|
|
|
|
+ }
|
|
|
|
|
+ this._pathArr.pop()
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 切换画笔
|
|
|
|
|
+ changeBrush(url = '') {
|
|
|
|
|
+ if (!url) return
|
|
|
|
|
+ const img = this._canvas.createImage()
|
|
|
|
|
+ img.onload = () => {
|
|
|
|
|
+ this._style = this._ctx.createPattern(img, 'repeat')
|
|
|
|
|
+ }
|
|
|
|
|
+ img.src = url
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 清除画布
|
|
|
|
|
+ destory() {
|
|
|
|
|
+ this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height)
|
|
|
|
|
+ this._pathArr = []
|
|
|
|
|
+ this._executionArr = []
|
|
|
|
|
+ this._style = null
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 保存
|
|
|
|
|
+ save() {
|
|
|
|
|
+ wx.canvasToTempFilePath({
|
|
|
|
|
+ canvas: this._canvas,
|
|
|
|
|
+ success(res) {
|
|
|
|
|
+ console.log('保存', res.tempFilePath);
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+export { DrawCanvas }
|