欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信小程序实现canvas预览图片打水印

程序员文章站 2024-02-11 16:57:58
...

微信小程序实现canvas预览图片打水印微信小程序实现canvas预览图片打水印
先给用户展示没经过处理原图,如果用户需要保存为图片,就在点击预览的时候添加水印,本来想在用户保存为图片的时候在添加水印,文档好像没有这方面的监听。

<view>
    <view class="poster">
        <image src="{{img_url}}" data-img="{{img_url}}" bindtap="getpreview"></image>
    </view>
    <canvas class="draw" style="width: {{img_width}}px;height:{{img_height}}px;" canvas-id="mycanvas"></canvas>
</view>
.poster {
    width: 300rpx;
    height: 300rpx;
}

.poster image {
    width: 100%;
    height: 100%;
}

.draw {
    position: absolute;
    top: -9999rpx;
    opacity: 0;
}
Page({
  data: {
    img_url: "https://sucai.suoluomei.cn/sucai_zs/images/20191221105424-bg.png",
    img_width: '',
    img_height: '',
    logo_url: '',
    logo_width: '',
    logo_height: ''
  },
  onLoad: function (options) {},
  getpreview(e) {
    wx.showLoading({
      title: '加载中',
    })
    var picture = e.currentTarget.dataset.img
    //需要打水印的图片
    wx.getImageInfo({
      src: picture,
      success: (res) => {
        picture = res.path
        this.setData({
          img_width: res.width,
          img_height: res.height
        })
      }
    })
    //水印图片
    wx.getImageInfo({
      src: 'https://sucai.suoluomei.cn/sucai_zs/images/20190919150508-logo.png',
      success: (res) => {
        this.setData({
          logo_url: res.path,
          logo_width: res.width,
          logo_height: res.height
        })
      }
    })
    setTimeout(() => {
      wx.hideLoading()
      let ctx = wx.createCanvasContext('mycanvas')
      ctx.drawImage(picture, 0, 0, this.data.img_width, this.data.img_height)
      ctx.drawImage(this.data.logo_url, this.data.img_width - 120, this.data.img_height - 80, this.data.logo_width, this.data.logo_height)
      ctx.draw(true, () => {
        wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          success: (res) => {
            wx.previewImage({
              current: res.tempFilePath,
              urls: [res.tempFilePath]
            })
          },
        })
      })
    }, 800)
  },
})
相关标签: Weapp