小程序使用 canvas 给图片添加水印

news/2024/7/20 2:28:46 标签: 小程序, javascript, 前端

小程序使用 canvas 给图片添加水印

操作 canvas 相关的 api 使用的是微信最新提供的 (一路过来踩了好多坑…)

浅用微信小程序 canvas 给图片添加简单水印, 废话不多说, 先上效果, 后看代码 (uniapp等框架写法大同小异)

效果图

6901c35965fc25fbcf08fa61269e7dd.jpg

464e6e80ca6dd6bce029b696920f2f1.jpg

代码部分 (没有细分拆开来讲, 但大部分代码都加解释注释了)

WXML

<view class="container">
  <button bindtap="chooseImages">选择图片</button>
  <view>
    <image src="{{imgsrc}}" mode="aspectFit" bindtap="prevImage"></image>
  </view>
</view>
<canvas style="position:fixed;top: 0;left: -100%" type="2d" id="Canvas"></canvas>

JavaScript

Page({
  data: {
    imgsrc: '',
    canvas: null,
    ctx: null,
  },
  // 在页面初次渲染完成生命周期获取操作canvas的上下文对象
  onReady() {
    const query = wx.createSelectorQuery()
    query.select('#Canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        this.setData({ canvas, ctx })
      })
  },
  // 选择图片
  async chooseImages() {
    const res = await wx.chooseImage({})
    const addWatermarkRes = await this.addWatermark(res.tempFilePaths[0])
  },
  // 添加水印方法 (传入图片地址)
  addWatermark(tempFilePath) {
    return new Promise( async (resolve, reject) => {
        // 获取图片信息
        const imgInfo = await wx.getImageInfo({ src: tempFilePath })
        // 设置canvas宽高
        this.data.canvas.width = imgInfo.width
        this.data.canvas.height = imgInfo.height
        // 创建一个图片对象
        const image = this.data.canvas.createImage();
        image.src = tempFilePath;
        image.onload = () => {
          // 将图片绘制到canvas上
          this.data.ctx.drawImage(image, 0, 0, imgInfo.width, imgInfo.height)
          // 设置文字字号及字体
          this.data.ctx.font = '32px sans-serif'
          // 设置画笔颜色
          this.data.ctx.fillStyle = 'rgba(0,0,0,0.3)';
          // 绘制矩形
          this.data.ctx.fillRect(0, imgInfo.height - 40, 420, 40)
          // 设置画笔颜色
          this.data.ctx.fillStyle = '#ffffff';
          // 填入文字
          this.data.ctx.fillText('品名: 巨无霸汉堡; 单价: 20元', 0, imgInfo.height - 10)
          // 将canvas转为为图片
          wx.canvasToTempFilePath({
            canvas: this.data.canvas,
            success: (res) => {
              this.setData({ imgsrc: res.tempFilePath})
              resolve(res.tempFilePath)
            },
          })
        }
    })
  },
  // 预览图片
  prevImage(){
    wx.previewImage({
      current: this.data.imgsrc, // 当前显示图片的http链接
      urls: [this.data.imgsrc] // 需要预览的图片http链接列表
    })
  }
})

有问题可以评论区或者私信讨论哈


http://www.niftyadmin.cn/n/875390.html

相关文章

微信小程序常见网络请求失败问题总结及解决方案

微信小程序常见网络请求失败问题总结及解决方案 微信开发者工具中未勾选不校验合法域名设置 未勾选这个设置在任何环境下发送http网络请求会失败 发送的是https请求&#xff0c;但网络请求依旧是失败 需要到官方的微信小程序后台的 开发管理 -> 开发设置 -> 服务器域…

uni-app一键复制到剪切板,无需插件

<template><text click"copyBtn()">复制</text> </template> export default{methods:{copyBtn: function() {uni.setClipboardData({data: 需要复制的内容 ,success: function () {uni.showToast({title: 复制成功,});},fail:function () …

前端实习总结

菜鸟自述 还是感叹一下时间的飞逝&#xff0c;大学一直在寻找&#xff0c;自己将来到底要干嘛&#xff1f;好在虽然学校老师教得不多&#xff0c;安排的项目到是挺多&#xff0c;做过不同类型的项目&#xff0c;做过pc端网站&#xff0c;pe端网站&#xff0c;其实也是&#xf…

自定义浏览器滚动条样式

//滑槽样式 .leftBox::-webkit-scrollbar {width: 6px;background: #DDF0FF;border-radius: 6px;padding-bottom: 5px; } //滑块样式 .leftBox::-webkit-scrollbar-thumb {background: #3D93FD;border-radius: 6px; }

前端将后台传的文件流下载为文件到本地

后台将excel文件解析为流的形式返给前端&#xff0c;前端拿到数据完成下载。利用XMLHttpRequest&#xff0c;具体代码实现如下&#xff1a; var oReq new XMLHttpRequest(); //url参数为拿后台数据的接口 oReq.open("POST",url, true); oReq.responseType "b…

openlayers在加载百度地图的基础上加要素图层

注意&#xff1a; 这个方法是openlayers加载百度的在线服务瓦片图层&#xff0c;openlayers加载百度地图坐标会有偏差&#xff0c;引入一个坐标转换源文件即可&#xff0c;这种方法可以将偏差降低最小&#xff0c;文件内容参照https://blog.csdn.net/du_5pet/article/details/…

openlayers结合百度地图API加载搜索定位功能

//每次请求之前清空上一次搜索的图层 searchPlaceLayer.getSource().clear()$.ajax({//url中的参数含义参见百度地图官网webAPI文档url: http://api.map.baidu.com/place/v2/search?query大唐芙蓉园&region西安市&page_size40&page_num0&outputjson&ak你…

openlayers加载百度地图提示跨域

在项目中用ajax请求外部百度地图服务网址时提示跨域&#xff0c;只能前端用jsonp来解决了&#xff0c;就把你的ajax加上这些参数就行了 $.ajax({ url: url, type: "GET", async: false, dataType: "jsonp", jsonp…