大家好,又见面了,我是你们的朋友全栈君。
思路: 1.点击图片上传 2.加水印 3.传给后台 html
<canvas class='canvas' canvas-id="firstCanvas"></canvas>
css
.canvas{
border: 2rpx solid pink;
background: pink;
width: 100%;
height: 100%;
//position:fixed;left:100%; 想隐藏画布单又想执行画布方法,用这个css;用display会不执行画布
}
js
//点击方法上传
chooseImg: function () {
var that = this;
wx.showActionSheet({
itemList: ['手机拍摄', '图片上传'],
success: function (res) {
//if (res.tapIndex == 0) {
wx.chooseImage({
count: 3, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;//
for (let item of tempFilePaths) {
//that.uploadimg(item);//这是直接上传原图
}
if (that.data.imgList.length != 0) {
that.setData({
imgList: that.data.imgList.concat(res.tempFilePaths)
})
} else {
that.setData({
imgList: res.tempFilePaths
})
}
that.watermark();//调方法加水印
}
})
},
})
},
//加水印
watermark:function() {
let that = this
console.log(that.data.imgList,11111)//上传的图片
//获取图片详细信息
for (let item of that.data.imgList) {
wx.getImageInfo({
src: item,
success: (ress) => {
console.log("获取图片详情", item)
let ctx = wx.createCanvasContext('firstCanvas')
that.setData({
canvasHeight: ress.height,
canvasWidth: ress.width
})
//将图片src放到cancas内,宽高为图片大小
ctx.drawImage(item, 0, 0, 56, 56)
//将声明的时间放入canvas
ctx.setFontSize(17) //注意:设置文字大小必须放在填充文字之前,否则不生效
ctx.setFillStyle('grey')
ctx.fillText("水印", 0, 30)
ctx.strokeText("水印", 0, 30)
ctx.draw(false, function () {
wx.canvasToTempFilePath({
canvasId: 'firstCanvas',
success: (res) => {
that.uploadimg(res.tempFilePath);//上传图片,加了水印的图片
},
fail: (e) => {
console.log(e)
}
})
})
}
})
}
},
//上传图片
uploadimg(localUrl) {
let that = this;
wx.showLoading({
title: "正在上传图片",
mask: true
})
var tempFilePaths = [];
tempFilePaths.push(localUrl)
//这是公司封装的上传方法,就是ajax上传而已
ygPost.uploadFile(tempFilePaths, function (res) {
wx.hideLoading();
if (res) {
wx.showToast({
title: '图片上传成功',
icon: 'success',
duration: 1000
})
let arr = []
arr.push(res)
that.setData({
uploadList: that.data.uploadList.concat(arr)//加了水印的图片合集
})
console.log(that.data.uploadList, 1111)
wx.hideLoading();
}
})
},
//测试end
注意事项: 1.如果在画图完成后,有对应操作时,必须在draw的callback后执行,比如图片预览、改变画布大小等 ctx.draw(false, function() { console.log(‘后续操作’);
}) 2.draw完成后的图片预览 wx.canvasToTempFilePath({ x: 0, y: 0, width: width, height: height, canvasId: canvasId, fileType: ‘png’, success: function(res) { wx.previewImage({ urls: [res.tempFilePath], }) } }, ctx)
大概思路
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/148950.html原文链接:https://javaforall.cn