微信小程序图片加水印功能,使用新版Canvas 2D 接口实现。
【效果预览】- 微信扫一扫体验
【相关代码】
wxml:
<!-- 2d 类型的 canvas -->
<canvas type="2d" id="myCanvas"></canvas>
首先需要在 WXML 中添加 canvas 组件。
指定 id="myCanvas" 唯一标识一个 canvas,用于后续获取 Canvas 对象。
指定 type 用于定义画布类型,本例子使用 type="2d" 示例。
js:
/**
* 页面的初始数据
*/
data: {
imgsrc: '',
canvas: null,
ctx: null,
canvasWidth: 200,
canvasHeight: 200,
imgFilePath: '',
fontSize: 36,
rgba: 'rgb(255,255,255,0.5)',
angle: 45
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
const query = wx.createSelectorQuery()
query.select('#myCanvas')// 在 WXML 中填入的 id
.fields({ node: true, size: true })
.exec((res) => {
// Canvas 对象
const canvas = res[0].node
// 渲染上下文
const ctx = canvas.getContext('2d')
this.setData({ canvas, ctx })
})
},
// 添加水印方法 (传入图片地址)
addWatermark(tempFilePath) {
if (!tempFilePath) {
return
}
return new Promise( async (resolve, reject) => {
wx.showLoading({
title: '水印生成中...',
})
// 获取图片信息
const imgInfo = await wx.getImageInfo({ src: tempFilePath })
// 设置canvas宽高
this.data.canvas.width = imgInfo.width
this.data.canvas.height = imgInfo.height
this.data.canvasWidth = imgInfo.width
this.data.canvasHeight = 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)
//水印文字样式相关
let maskText = '仅供XX使用'; //水印文字
let fontColor = this.data.rgba;
let textWidth = this.data.fontSize * maskText.length; //水印文字宽度
let jd = this.data.angle;//角度
this.data.ctx.save()
let interval = textWidth
for (let x = 0; x < this.data.canvasWidth; x += interval ) {
for (let y = 0; y < this.data.canvasHeight; y += interval ) {
this.data.ctx.translate(x, y)
this.data.ctx.rotate(jd * Math.PI / 180)
this.data.ctx.font = this.data.fontSize + 'px Arial'
this.data.ctx.fillStyle = fontColor
this.data.ctx.fillText(maskText, 0, 0);
this.data.ctx.restore()
this.data.ctx.save()
}
}
this.data.ctx.restore()
// 将canvas转为图片
wx.canvasToTempFilePath({
canvas: this.data.canvas,
success: (res) => {
wx.hideLoading()
this.setData({ imgsrc: res.tempFilePath })
resolve(res.tempFilePath)
},
})
}
})
},
源代码下载: