uniapp图片添加水印

先贴代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<template>
<view>
<button type="primary" @tap="takePhoto">拍照</button>
<image style="width: 100%;" mode="widthFix" :src="src" @click="preview"></image>
<view style="position: absolute;top: -999999px;">
<view><canvas :style="{ width: w, height: h }" canvas-id="firstCanvas"></canvas></view>
</view>
</view>
</template>

<script>
export default {
data() {
return {
src: '',
w: '',
h: ''
};
},
methods: {
preview() {
uni.previewImage({
urls: [this.src],
current: 0
});
},
takePhoto() {
var that = this;
uni.chooseImage({
count: 1,
success(res) {
uni.getImageInfo({
src: res.tempFilePaths[0],
success: ress => {
// 显示加载框
uni.showLoading({
title: '水印制作中',
mask: true
});

that.w = ress.width / 3 + 'px';
that.h = ress.height / 3 + 'px';

// ********************************重要setTimeout********************************
setTimeout(() => {
let ctx = uni.createCanvasContext('firstCanvas'); /** 创建画布 */
//将图片src放到cancas内,宽高为图片大小
ctx.drawImage(res.tempFilePaths[0], 0, 0, ress.width / 3, ress.height / 3);
ctx.setFontSize(18);
ctx.setFillStyle('#8a2929');
ctx.rotate((30 * Math.PI) / 180);
let textToWidth = (ress.width / 3) * 0.5;
let textToHeight = (ress.height / 3) * 0.3;
ctx.fillText('我是水印', textToWidth, textToHeight);
/** 除了上面的文字水印,这里也可以加入图片水印 */
//ctx.drawImage('/static/watermark.png', 0, 0, ress.width / 3, ress.height / 3)
ctx.draw(false, () => {
uni.canvasToTempFilePath({
canvasId: 'firstCanvas',
success: res1 => {
that.src = res1.tempFilePath;
uni.hideLoading();
}
});
});
}, 500);
}
});
}
});
}
}
};
</script>

<style></style>

其中最重要的地方就是延迟设置位置,担心尺寸重置后还没生效,故做延迟,而不要将延迟放在 draw 里面

结果:


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!