1. 程式人生 > 程式設計 >微信小程式canvas擷取任意形狀的實現程式碼

微信小程式canvas擷取任意形狀的實現程式碼

最近在研究拼圖驗證碼實現,需要對圖片的部分模組進行特殊形狀切割出一小塊,明白後原來是如此簡單,第一步就是將所有繪製的形狀用線勾出(直線、弧線、貝塞爾曲線都可以)形成閉環,第二步就是切割繪製,第二步不麻煩,麻煩的只是第一步,需要一些計算,所以會在以後,盡力的多儲存一些特殊形狀的方法。

比如:

程式碼

drawPic(x,y,r){
  // const ctxBackground = wx.createCanvasContext('canvasBackground')
  const ctxBackground = wx.createCanvasContext('canvasBackground')
  ctxBackground.save();
  //開始一個新的繪製路徑
  ctxBackground.beginPath();
  //設定路徑起點座標
  ctxBackground.moveTo(x,y);
  ctxBackground.arcTo(x,y - r,x + r,r);
  ctxBackground.lineTo(x + 2 * r,y - r);
  ctxBackground.arcTo(x + 2 * r,y - 2 * r,x + 3 * r,r);
  ctxBackground.arcTo(x + 4 * r,x + 4 * r,r);
  ctxBackground.lineTo(x + 5 * r,y - r);
  ctxBackground.arcTo(x + 6 * r,x + 6 * r,r);
  ctxBackground.lineTo(x + 6 * r,y + r);
  ctxBackground.arcTo(x + 7 * r,y + r,x + 7 * r,y + 2 * r,r);
  ctxBackground.arcTo(x + 7 * r,y + 3 * r,y + 4 * r);
  ctxBackground.arcTo(x + 6 * r,y + 5 * r,x + 5 * r,r);
  ctxBackground.lineTo(x + 4 * r,y + 5 * r);
  ctxBackground.arcTo(x + 4 * r,y + 4 * r,r);
  ctxBackground.arcTo(x + 2 * r,x + 2 * r,r);
  ctxBackground.lineTo(x + r,y + 5 * r);
  ctxBackground.arcTo(x,x,r);
  ctxBackground.lineTo(x,y + 3 * r);
  ctxBackground.arcTo(x + r,r);
  ctxBackground.arcTo(x + r,y);
  //先關閉繪製路徑。注意,此時將會使用直線連線當前端點和起始端點。
  ctxBackground.closePath();
  ctxBackground.clip();
  ctxBackground.stroke(); //畫線輪廓
  wx.getImageInfo({
   src: 'cloud://normal-env/000060.jpg',success: function (res) {
    ctxBackground.drawImage(res.path,256,191);
    ctxBackground.restore();
    ctxBackground.draw();
   }
  })
 }

總結

以上所述是小編給大家介紹的微信小程式canvas擷取任意形狀的實現程式碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!