微信小程序:手寫板功能實(shí)現(xiàn)(canvas)

在微信小程序中,同樣支持canvas的使用。

1.首先在 wxml 頁面中添加<canvas></canvas>組件:

<canvas class="sign" canvas-id="sign" bindtouchmove="move" bindtouchstart="start" bindtouchend="end" bindtouchcancel="cancel" bindlongtap="tap" disable-scroll="true" binderror="error">
</canvas>

2.在小程序的 js 中初始化所需的變量如下:

// 初始化簽名變量,放在 Page 前
var content = null;
var touchs = [];
//頁面的data數(shù)據(jù),在 Page 中
data: {
    imgList:[],
    signImage: ''
  }

3.在小程序的 js 中 Page 內(nèi)寫入如下函數(shù):


  // 畫布的觸摸移動(dòng)開始手勢響應(yīng)
  start: function (event) {
    // console.log("觸摸開始" + event.changedTouches[0].x);
    // console.log("觸摸開始" + event.changedTouches[0].y);
    //獲取觸摸開始的 x,y
    let point = { x: event.changedTouches[0].x, y: event.changedTouches[0].y }
    touchs.push(point);
  },
  // 畫布的觸摸移動(dòng)手勢響應(yīng)
  move: function (e) {
    let point = { x: e.touches[0].x, y: e.touches[0].y }
    touchs.push(point);
    if (touchs.length >= 2) {
      this.draw(touchs);
    }
  },
  // 畫布的觸摸移動(dòng)結(jié)束手勢響應(yīng)
  end: function (e) {
    console.log("觸摸結(jié)束" + e);
    //清空軌跡數(shù)組
    for (let i = 0; i < touchs.length; i++) {
      touchs.pop();
    }
  },
  // 畫布的觸摸取消響應(yīng)
  cancel: function (e) {
    console.log("觸摸取消" + e);
  },
  // 畫布的長按手勢響應(yīng)
  tap: function (e) {
    console.log("長按手勢" + e);
  },
  error: function (e) {
    console.log("畫布觸摸錯(cuò)誤" + e);
  },
  /**
  * 生命周期函數(shù)--監(jiān)聽頁面加載
  */
  onLoad: function (options) {
    //獲得Canvas的上下文
    content = wx.createCanvasContext('sign');
    //設(shè)置線的顏色
    content.setStrokeStyle("#000");
    //設(shè)置線的寬度
    content.setLineWidth(3);
    //設(shè)置線兩端端點(diǎn)樣式更加圓潤
    content.setLineCap('round');
    //設(shè)置兩條線連接處更加圓潤
    content.setLineJoin('round');
  },
  //繪制
  draw: function (touchs) {
    let point1 = touchs[0];
    let point2 = touchs[1];
    touchs.shift();
    content.moveTo(point1.x, point1.y);
    content.lineTo(point2.x, point2.y);
    content.stroke();
    content.draw(true);
  },
  //清除操作
  clearClick: function () {
    //清除畫布
    content.clearRect(0, 0,750, 700);
    content.draw(true);
  },
  //保存圖片
  saveClick: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'firstCanvas',
      success: function (res) {
        //打印圖片路徑
        console.log(res.tempFilePath);
        //設(shè)置保存的圖片
        that.setData({
          signImage: res.tempFilePath
        })
      }
    })
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容