­

乾貨 | 用uni-app製作迷你PS小程序

  • 2020 年 2 月 24 日
  • 筆記

該文章主要講解最近基於 uni-app 框架編寫的集圖文拖拽等多方位編輯、油墨電子簽名、開放式海報於一體的小程序的製作思路和實現代碼。

1、完整源碼鏈接:

完整代碼:https://github.com/TensionMax/mini-ps

其中演示的文字編輯、圖片編輯、油墨電子簽名、開放式海報可單獨使用,含文檔說明。

2、實現思路

該工具主要由五個不同組件模塊:文字編輯、圖片編輯,油墨電子簽名、控制、開放式海報

1、文字編輯模塊設置好的文字參數對象插入到文字隊列中。

2、圖片編輯模塊設置好的圖片參數對象插入到圖片隊列中。

3、油墨電子簽名模塊完成繪製後轉為利用 canvasToTempFilePath 轉成臨時圖片,獲取參數後插入圖片隊列中,也可以直接導出。

4、利用控制模塊調整/文字隊列和圖片隊列的參數。

5、開放式海報模塊,利用控制台的參數將PS畫板上的效果繪製到canvas上來實現的效果,接着再利用 canvasToTempFilePath 轉成圖片導出。

3、核心代碼

3-1、文字/圖片編輯模塊

文字/圖片編輯模塊主要是實現移動/縮放功能,其他附帶的屬於甜品,

由於兩個模塊功能類似,該篇僅講解圖片編輯模塊。

HTML

<img   style="position: absolute"   :style="{       left: item.x+'px',       top: item.y+'px',       width: item.w+'px',       height: item.h+'px',       }"    @touchstart='touchStart($event,item,index)'    @longpress='longPress($event,item,index)'    @touchmove.stop='touchMove($event,item,index)'    @touchcancel="touchEnd($event,item,index)"    @touchend='touchEnd($event,item,index)'    v-for="(item,index) of imagelist"    :key="index"    :src="item.src"    />

在 imageList 的數組標籤中,每個綁定的事件中用 $event 來調用事件本身的參數,其中 $event 的 touches 或 changedTouches 包含我們需要的位置參數,示例如下:

touches:[{          clientX: 14 //與顯示區域(不含頂部欄)左上角的水平距離          clientY: 16 //與顯示區域(不含頂部欄)左上角的垂直距離          pageX: 14 //與整個頁面(不含頂部欄)左上角的水平距離          pageY: 16 //與整個頁面(不含頂部欄)左上角的垂直距離          },          {          clientX: 14          clientY: 16          pageX: 14          pageY: 16          }]

touches 長度為2代表雙指觸碰,通過判定雙指觸摸點的變化方向可實現雙指縮放效果。因為每個標籤都設置為 style="position: absolute" 所以只需要根據位置參數來更新 x、y、w、h 即可

題外話-性能問題

① 一次移動多次操作DOM影響性能

—— 虛擬DOM了解一下

② 為何不用事件委派?

—— 不必要,Vue已經幫我們做了優化,在非常影響性能時再考慮

3-2、油墨電子簽名板

由於 touchmove 事件在小程序真機的觸發頻率和精確度很迷,不太好根據速度來判定繪製的線寬,我只好用其他方式去實現,雖然效果不完美。

其實現思路是通過多次的循環繪製以達到油墨效果,每次循環繪製的長度和寬度都不相同。

HTML

<canvas  canvas-id="canvas"  @touchstart.stop="touchStart"  @touchmove.stop="touchMove"  @touchend.stop="touchEnd"  >  </canvas>

JAVASCRIPT

export default {  data() {      return {          lineWidth0: 5, //初始線寬 建議1~5          ctx: null,          x0: 0, //初始橫坐標或上一段touchmove事件中觸摸點的橫坐標          y0: 0, //初始縱坐標或上一段touchmove事件中觸摸點的縱坐標          t0: 0, //初始時間或上一段touchmove事件發生時間          v0: 0, //初始速率或touchmove事件間發生速率          lineWidth: 0, //動態線寬          keenness: 5, //油墨程度 建議0~5          k: 0.3, //油墨因子,即每次繪製線條時線寬的變化程度      }  },  onReady() {      this.ctx = uni.createCanvasContext('canvas', this);      this.ctx.setLineCap('round')  },  methods: {      //設置初始值      touchStart(e) {          this.lineWidth = this.lineWidth0          this.t0 = new Date().getTime()          this.v0 = 0          this.x0 = e.touches[0].clientX          this.y0 = e.touches[0].clientY      },        touchMove(e) {          let dx = e.touches[0].clientX - this.x0,              dy = e.touches[0].clientY - this.y0,              ds = Math.pow(dx * dx + dy * dy, 0.5),              dt = (new Date().getTime()) - this.t0,              v1 = ds / dt; //同 this.v0 初始速率或touchmove事件間發生速率          if (this.keenness === 0) { //油墨為0時              this.ctx.moveTo(this.x0, this.y0)              this.ctx.lineTo(this.x0 + dx, this.y0 + dy)              this.ctx.setLineWidth(this.lineWidth)              this.ctx.stroke()              this.ctx.draw(true)          } else {              //由於touchMove的觸發頻率問題,這裡採用for循環繪製,原理如圖所示              //這裡的k因為              let a = this.keenness              if (this.keenness > 5) {                  a = 5              }              for (let i = 0; i < a; i++) {                  this.ctx.moveTo(this.x0 + dx * i / a, this.y0 + dy * i / a)                  this.ctx.lineTo(this.x0 + dx * (i + 1) / a, this.y0 + dy * (i + 1) / a)                  //此時touchmove事件間發生與上一個事件的發生的速率比較                  if (v1 < this.v0) {                      this.lineWidth -= this.k                      if (this.lineWidth < this.lineWidth * 0.25) this.lineWidth = this.lineWidth * 0.25                  } else {                      this.lineWidth += this.k                      if (this.lineWidth > this.lineWidth * 1.5) this.lineWidth = this.lineWidth * 1.5                  }                  this.ctx.setLineWidth(this.lineWidth)                  this.ctx.stroke()                  this.ctx.draw(true)              }          }          this.x0 = e.touches[0].clientX          this.y0 = e.touches[0].clientY          this.t0 = new Date().getTime()          this.v0 = v1      },      touchEnd(e) {          this.x0 = 0          this.y0 = 0          this.t0 = 0          this.v0 = 0      }  }  }

使用的大部分是canvas的基礎api,注意繪製單位都為px。

油墨電子簽名Demo

3-3、開放式海報模塊

如果說微信小程序是銀色金灘,那麼截至2020年1月6日或者未來,小程序的canvas就是金灘上充斥着未知數個的玻璃塊的那一片 ——

魯迅

說起小程序canvas,那bug不是一般的多,部分不常見bug我會在代碼注釋里說明。

HTML

<canvas canvas-id="generate" :style="{ width: canvasW + 'rpx', height: canvasH + 'rpx'}"></canvas>

如果圖片是網絡路徑,記得獲取臨時路徑。

//別忘了在函數前加 asynclet src = 'https://s2.ax1x.com/2020/01/05/lrCDx0.jpg'  src = (await uni.getImageInfo({src}))[1].path;

JAVASCRIPT輸出字段部分

//為方便設置,以下除角度外,單位均以rpx為主  data() {      return {          canvasW:720,          canvasH:1000,          img:[{              src: 'https://s2.ax1x.com/2020/01/05/lrCDx0.jpg',              x: 0,              y: 0,              w: 100,              h: 100,              r: 50,//圓角度              degrees: 30,//旋轉度              mirror: true//是否鏡像              }],          text:[{                  content: 'TensionMax',                  x: 50,                  y: 50,                  w: 100,                  lineHeight: 35,//行間距                  color: '#000000',                  size: 28,                  weight: 'normal',//字體粗細                  lineThrough: true,//是否貫穿              }],          ctx: null,          k: null //單位轉換因子      };  }

JAVASCRIPTrpx 或 upx與 px 的單位統一轉換方法

px2rpx() {      //當轉換的參數只有一個時直接返回數值如      //當不為一個時返回數組,然後用spread語法將其展開為幾個參數      //Math.floor()是為了防止在安卓機上造成的數據紊亂,開發者工具無此bug      if (arguments.length === 1) return Math.floor(arguments[0] / this.k)      let params = []      for (let i of arguments) {          params.push(Math.floor(i / this.k))      }      return params  },  rpx2px() {      if (arguments.length === 1) return Math.floor(arguments[0] * this.k)      let params = []      for (let i of arguments) {          params.push(Math.floor(i * this.k))      }      return params  },

JAVASCRIPT繪製圖片的函數

async drawImg() {  this.ctx.setFillStyle('#FFFFFF')  this.ctx.fillRect(0, 0, ...this.rpx2px(this.canvasW, this.canvasH)) //繪製背景  for (let i of this.img) { //for循環繪製圖片      i.src = (await uni.getImageInfo({src: i.src}))[1].path;//獲取圖片臨時路徑      this.ctx.save() //保存當前繪製內容      if (i.mirror) { //如果設置鏡像          //因為canvas的translate屬性是基於原點(初始原點為右上角)變化          //所以需要先將原點移動至圖片中心,變化後再還原          //旋轉變化同理          this.ctx.translate(...this.rpx2px(i.x + i.w / 2, i.y + i.h / 2))          this.ctx.scale(-1, 1)          this.ctx.translate(...this.rpx2px(-i.x - i.w / 2, -i.y - i.h / 2))      }      if (i.degrees) { //如果設置旋轉          this.ctx.translate(...this.rpx2px(i.x + i.w / 2, i.y + i.h / 2))          this.ctx.rotate(i.degrees * Math.PI / 180)          this.ctx.translate(...this.rpx2px(-i.x - i.w / 2, -i.y - i.h / 2))      }      this.radiusRect(...this.rpx2px(i.x, i.y, i.w, i.h, i.r)) //圓角或矩形路徑繪製      this.ctx.clip() //裁剪      this.ctx.drawImage(i.src, ...this.rpx2px(i.x, i.y, i.w, i.h))      this.ctx.restore() //恢復非裁剪區域  }  this.ctx.draw(true)  }    radiusRect(x, y, w, h, r) {      if (r > w / 2 || r > h / 2) {          r = Math.min(w, h) / 2      }      this.ctx.beginPath();      this.ctx.moveTo(x, y); // 將操作點移至左上角      this.ctx.arcTo(x + w, y, x + w, y + r, r); // 畫右上角的弧      this.ctx.lineTo(x + w, y) //可省略,但由於安卓真機的小程序bug,留之,下同。      this.ctx.arcTo(x + w, y + h, x + w - r, y + h, r); // 畫右下角的弧      this.ctx.lineTo(x + w, y + h) //可省略      this.ctx.arcTo(x, y + h, x, y + h - r, r); // 畫左下角的弧      this.ctx.lineTo(x, y + h) //可省略      this.ctx.arcTo(x, y, x + r, y, r); // 畫左上角的弧      this.ctx.lineTo(x, y) //可省略  },

繪製自定義文字

文字繪製稍微麻煩些,主要是canvas不會自動幫我們換行排版,網上類似的實現方法太多,該篇就不講,直接放在Demo裏面。

3-4、小結

既然我們知道了這幾個組件自定義調整參數的方式,那麼最後只需要一個父組件作為控制台來調整他們的參數即可,可以通過 props 、 sync 修飾符 等來實現父子通信,當然如果想做更複雜的可以考慮用 Vuex 傳參。接下來就可以根據這思路來實現繁瑣的業務邏輯了。

4、效果展示

效果圖如下,歡迎到下方評論區討論交流。

原文作者:Rolan

原文鏈接:http://www.wxapp-union.com/article-5785-1.html

好課推薦

點擊閱讀原文報名學習騰訊NEXT學院

「uni-app商業級應用實戰」

不會用後台開發,

也能做出很秀的app!

一指禪 戳戳可免費試學!