小程序 canvas实现图片预览,图片保存

wxml 代码:

<view class="result-page">
 <canvas  bindtap="previewImage" canvas-id='myPicCanvas' style='width:100%;height:600px;margin: 0;padding: 0;display: block;background-color:#eeeeee'></canvas>
  <button  bindtap="savePic">保存图片</button>
</view>

js代码:

/**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.drawCanvasPic();
    
  },
  previewImage: function () {
    console.log(1);
    wx.canvasToTempFilePath({
      canvasId: 'myPicCanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        wx.previewImage({
          current: tempFilePath, // 当前显示图片的http链接  
          urls: [tempFilePath] // 需要预览的图片http链接列表  
        })
      },
      fail: function (res) {
        console.log(res);
      }
    });

  },
  drawCanvasPic: function () {
    let ctx = wx.createCanvasContext('myPicCanvas');
    let ctxW = 100;
    let ctxH = 700;
    // 默认像素比

    // 屏幕系数比,以设计稿375*667(iphone7)为例
    let XS =  375;

    
    /* 绘制头像 */
    let avatarurl_width = 100;    //绘制的头像宽度
    let avatarurl_heigth = 100;   //绘制的头像高度
    let avatarurl_x = 50;   //绘制的头像在画布上的位置
    let avatarurl_y = 50;   //绘制的头像在画布上的位置
    ctx.save();

    ctx.beginPath(); //开始绘制
    //先画个圆   前两个参数确定了圆心 (x,y) 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false,即顺时针
    ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);

    ctx.clip();//画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域,则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
    
    ctx.drawImage('https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2369419058,1797305489&fm=27&gp=0.jpg', avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); // 推进去图片,必须是https图片

    ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制 

    ctx.draw(); //可将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中
  },
  savePic: function (e) {
    console.log(111);
    wx.canvasToTempFilePath({
      canvasId: 'myPicCanvas',
      success: function (res) {
        console.log(res);
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(result) {
            wx.showToast({
              title: '图片保存成功',
              icon: 'success',
              duration: 2000
            })
          }
        })
      }
    })
  },

猜你喜欢

转载自www.cnblogs.com/-mrl/p/9089503.html