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>
js
// index.js
// 获取应用实例
const app = getApp()
let textCtx;
Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
canIUseGetUserProfile: false,
canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
ishow: false
},
// 事件处理函数
bindViewTap() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
wx.onUserCaptureScreen(function (res) {
console.log('用户截屏了')
})
let that = this
let canvas = null;
const dpr = wx.getSystemInfoSync().pixelRatio
const rpx = wx.getSystemInfoSync().windowWidth
// canvas定位都是以px为单位
// rpx转换为px:
// rpx单位大小 / 750 * wx.getSystemInfoSync().windowWidth = px单位大小
let xMargin = 10 / 750 * rpx //画布侧边距
let yMargin = 20 / 750 * rpx //画布上下边距
let lMargin = 10 / 750 * rpx + 2 //行距
let textSize = parseInt(32 / 750 * rpx) //字体大小
const textWidth = parseInt((398 / 750) * rpx); // 列表定宽,超出换行显示
const secondLineHeight = parseInt((38 / 750) * rpx); // 一行超出,第二行多出的高度
let imgWidth = parseInt(200 / 750 * rpx) //图片宽
let imgHeight = parseInt(200 / 750 * rpx) //图片高
let imgMarginTop = 20 / 750 * rpx + 2 //图片高
},
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 = '100px 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('11111', 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链接列表
})
}
})