一、页面
<template>
<view>
<view @click="creatPic">生成图片</view>
<image :src="creatUrl" v-if="creatUrl"
:style="{'width':'350px','height':cHeight+'px'}">
</image>
<canvas :style="{'width': '350px','height':
cHeight+'px','position':'fixed','left':'100%'}" canvas-id="myCanvas"></canvas>
</view>
</template>
<script>
export default {
data() {
return {
cHeight:750,//画布高度
url:'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg',
//要加图片的水印
creatUrl:''
};
},
methods: {
creatPic(){
let obj = {
src: this.url,
first: `时间:2024-03-28`,
second: `滴滴滴滴点`,
three: `滴滴滴滴点2`,
four: `滴滴滴滴点3`,
five: `滴滴滴滴点4`,
}
let res = await this.getWatermark(obj)
if(res.tempFilePath){
this.creatUrl=res.tempFilePath
}else{
console.log('失败')
}
},
getWatermark(obj) {
return new Promise((resolve, reject) => {
let that = this;
uni.getImageInfo({
src: obj.src,
success: (ress) => {
let ctx = uni.createCanvasContext('myCanvas', that); //创建画布
let width = 350
let height = width / (ress.width / ress.height) //计算宽高比例
that.cHeight = height
ctx.drawImage(obj.src, 0, 0, width, height);
ctx.fillStyle = "rgba(0,0,0,0.3)";
ctx.fillRect(0, 0, width, 90); //为水印加了背景
ctx.font = '12px Arial'
ctx.setFillStyle('#FFFFFF') //字体颜色
ctx.fillText(obj.first, 10, 20)
ctx.fillText(obj.second, 10, 35)
ctx.fillText(obj.three, 10, 50)
ctx.fillText(obj.four, 10, 65)
ctx.fillText(obj.five, 10, 80)
ctx.draw(false, () => {
// setTimeout(() => { //制作复杂的水印需要时间,这里最好设置定时
uni.canvasToTempFilePath({ //内容转成图片
width: width, // 画布宽度
height: height, // 画布高度
x: 0,
y: 0,
fileType: 'jpg',//生成的图片类型
canvasId: "myCanvas",//canvasId
quality: 0.5,//图片质量
success: (res) => {
resolve(res);
},
fail: (err) => {
resolve(false);
}
}, that)
// }, 200)
});
},
fail: (err) => {
resolve(false);
}
})
})
}
}
};
</script>