下面的代码主要就是你在小程序调用了相机或者相册后,在返回的照片上添加水印。
WXML
<view style="width: 0;height: 0;overflow: hidden;position:fixed;left: 200%;">
<canvas canvas-id="firstCanvas" class="canvas" style="width: {{w}}px;height: {{h}}px;"></canvas>
</view>
JS
Photograph(){ //点击拍照的方法
let that = this
wx.chooseImage({
count: 1,//允许的上传总数
quality: 'high',//图片质量
sizeType: ['compressed'],
sourceType: ['camera'],//支持相机和相册
success: function(res) {
console.log(res.tempFilePaths[0])
wx.showLoading({
title: "正在加载图片",
mask: true
})
//获取原图片信息
wx.getImageInfo({
src: res.tempFilePaths[0],
success: function (res) {
console.log(res)
var width = res.width, height = res.height;
that.setData({//设定画布的宽高
w: width,
h: height
})
//获取当前时间
let newDate = new Date();
let year = newDate.getFullYear() //年
let month = newDate.getMonth() + 1 //月
let day = newDate.getDate() //日
var hour = newDate.getHours()
var minute = newDate.getMinutes()
var second = newDate.getSeconds()
let roleNameInfo = '拍摄时间:' + year + '年' + month + '月' + day + '日 '+hour+':'+minute+':' +second
//创建canvas
const ctx = wx.createCanvasContext('firstCanvas');
ctx.drawImage(res.path, 0, 0, width, height); //先画出图片
//将声明的时间放入canvas
ctx.setFontSize(24) //注意:设置文字大小必须放在填充文字之前,否则不生效
ctx.setFillStyle('black');
ctx.fillText(roleNameInfo, 60, height - 60);
ctx.draw(false, function () {
setTimeout(function(){
//绘画完成回调
//生成图片
wx.canvasToTempFilePath({
quality: 1,
fileType: 'jpg',
canvasId: 'firstCanvas',
success: function (ress) {
console.log(ress)
wx.uploadFile({ //将带有水印的图片上传到服务器
url: app.globalData.site.webSite + '/api/v1/file/stream',
filePath: ress.tempFilePath,
name: 'file',
success(_res) {
let data = JSON.parse(_res.data);
if (data.success) {
console.log(data.data)
wx.hideLoading();
that.setData({
storesPhoto: data.data
})
}
}
})
wx.saveImageToPhotosAlbum({ //将带有水印的图片保存到相册里
filePath: ress.tempFilePath,
success(resp) {
}
})
console.log(ress.tempFilePath);//ress.tempFilePath就是带有水印的图片路径
}
})
},600)
})
}
})
}
})
},
这个因为我们的要求只加了时间,大家还想添加什么东西都可以在canvas里面画出来。