微信小程序canvas的撤销功能

小程序越来越简单,提供给开发者的api也越来越多,微信这个平台真的很厉害~~

-------------------

canvas画板在涂鸦的时候,一不小心画错了一步,想撤销上一步,还是在微信小程序中去实现这个功能,顿时卡住了,还是去翻百度,翻csdn、简书,总结了几个文档按照自己的思路想了一个简单的方案;

在微信小程序的api支持下是这么做的:一个动作start->move->end(cancel)就结束了,小程序有个api

saveCurrentDrawWorks: function () {
   wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 0,
      height: 0,
      destWidth: 0,
      destHeight: 0,
      canvasId: self.data.Id,
      success: function (res) {
         var imgPath = res.tempFilePath;
         var allDrawWorksPath = self.data.allDrawWorksPath;
         allDrawWorksPath.push(imgPath);
         self.setData({
            allDrawWorksPath: allDrawWorksPath,
         })
      },
      fail: res => {
         console.log('获取画布图片失败', res);

      }
   })
},

在每次start的时候调用保存图片的这个方法,将当前画布的图片保存在本地的数组中;

点击撤销的时候:

drawRevoke: function () {
   var allDrawWorksPath = self.data.allDrawWorksPath;
   if (allDrawWorksPath == null || allDrawWorksPath.length == 0 || allDrawWorksPath == undefined) {
      return;
   }

   var privWorksPath = allDrawWorksPath.pop();
   self.setData({
      allDrawWorksPath: allDrawWorksPath,
   })


   drawPath.pop();
   self.setPaintSize(self.data.LineWidth);
   self.setPaintColor(self.data.StrokeStyle);
   drawContext.drawImage(privWorksPath, 0, 0, screenWidth, screenHeight);
   drawContext.draw();

   if (allDrawWorksPath.length == 0) {
     
   }
},

删除保存数组中的最后一个图片地址,并重画这个地址的图片(drawImage);

大功告成~虽然简单,但确实想了很久,,如果有帮到你,我会很开心

你可能感兴趣的:(微信小程序canvas的撤销功能)