700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 小程序使用 canvas 给图片添加水印

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

时间:2020-04-23 12:14:17

相关推荐

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

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

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

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

效果图

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

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].nodeconst 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.widththis.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链接列表})}})

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。