一: 创建页面
<template>
<view style="box">
<image :src="imgUrl" mode="widthFix"></image>
<canvas :style="{width: canvasW + 'px',height: canvasH + 'px'}" canvas-id="canvasId"></canvas>
</view>
</template>
<script>
import {waterMark, getImgWidthHeight} from '../../utils/image_watermark_functions.js'
export default {
data() {
return {
canvasW: 0,
canvasH: 0,
imgUrl: ''
}
},
onLoad() {
getImgWidthHeight('https://img0.baidu.com/it/u=896214020,274705695&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800')
.then(res=> {
this.canvasW = res.width
this.canvasH = res.height
})
waterMark(
'canvasId',
'https://img0.baidu.com/it/u=896214020,274705695&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800',
'https://img.soogif.com/Ctvo0Fcl2iYMr9wB7J6fPOEvUam8xg9s.png')
.then(res => {
this.imgUrl = res
})
},
methods: {
}
}
</script>
<style scoped>
.box{
}
</style>
二:创建utils文件,创建image_watermark_functions.js
/**
*
* @param {*} canvasId canvas的id
* @param {*} basePath 底图
* @param {*} watermarkPath 水印
* @param {*} scaleFactor 水印的尺寸比例
* @param {*} seat 水印在主图上的位置
* @returns
*/
const waterMark = async (canvasId, basePath, watermarkPath, scaleFactor = 0.1, seat = 'BR') => {
return new Promise(async (resolve) => {
const context = uni.createCanvasContext(canvasId);
let base_img = await getImgWidthHeight(basePath);
// 加载水印图片
let watermarkImg = await getImgWidthHeight(watermarkPath);
// 计算缩放比例
const base_width = base_img.width;
const base_height = base_img.height;
const scale = Math.min(base_width / watermarkImg.width, base_height / watermarkImg.height) *
scaleFactor;
// 计算调整后的水印图片尺寸
const newWidth = watermarkImg.width * scale;
const newHeight = watermarkImg.height * scale;
// 在画布上绘制基础图片
context.drawImage(base_img.path, 0, 0);
// (context.width - newWidth) / 2, (context.height - newHeight) / 2
let x = 0
let y = 0
if (seat === 'TL') { // 左上
x = newWidth / 2
y = newHeight / 3
}
if (seat === 'TR') { // 右上
x = base_width - newWidth - newWidth / 2
y = newHeight / 3
}
if (seat === 'BL') { // 左下
x = base_width - newWidth - newWidth / 2
y = base_height - newHeight - newWidth / 3
}
if (seat === 'BR') { // 右下
x = newWidth / 2
y = base_height - newHeight - newWidth / 3
}
// 在画布上绘制调整后的水印图片
context.drawImage(watermarkImg.path, x, y, newWidth, newHeight);
context.draw()
setTimeout(() => {
uni.canvasToTempFilePath({
canvasId,
fileType: 'png',
success: (path) => {
uni.getFileSystemManager().readFile({
filePath: path.tempFilePath,
encoding: 'base64',
success: res => {
let base64 = 'data:image/jpeg;base64,' +
res.data; //不加上这串字符,在页面无法显示
return resolve(base64);
}
})
},
fail: (e) => {
console.log(e)
}
})
}, 100)
});
};
const getImgWidthHeight = async (src) => {
return new Promise(resolve => {
uni.getImageInfo({
src
}).then(res => {
console.log(res, 'img')
return resolve(res)
})
})
};
export { waterMark ,getImgWidthHeight}