页面添加水印的方法有很多,以下举例使用class定义的方法进行水印内容渲染:
1、新建文件:WatermarkClass.js
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
|
export default class WatermarkClass {
constructor({id= "watermarkID" , str = "" , fontSize = 18, width = 400, height = 400, fillStyle= "#333333" , opacity = 1 }) {
this .id = id;
this .str = str;
this .fontSize = fontSize;
this .width = width;
this .height = height;
this .fillStyle = fillStyle
this .opacity = opacity;
}
// 绘制水印
draw() {
if (document.getElementById( this .id) !== null ) {
document.body.removeChild(document.getElementById( this .id));
}
const canvas = document.createElement( "canvas" );
// 设置canvas画布大小
canvas.width = this .width;
canvas.height = this .height;
const ctx = canvas.getContext( "2d" );
ctx.rotate(-(15 * Math.PI) / 180); // 水印旋转角度
ctx.font = `${ this .fontSize}px Vedana`;
ctx.fillStyle = this .fillStyle;
ctx.textAlign = "center" ;
ctx.textBaseline = "middle" ;
this .str.split( "," ).forEach((item, index) => {
ctx.fillText(item, canvas.width / 2, canvas.height / 2 + (index * this .fontSize + 10)); // 水印在画布的位置x,y轴
});
const div = document.createElement( "div" );
div.id = this .id;
div.style.pointerEvents = "none" ;
div.style.top = "30px" ;
div.style.left = "10px" ;
div.style.opacity = this .opacity;
div.style.position = "fixed" ;
div.style.zIndex = "999999" ;
div.style.width = `${document.documentElement.clientWidth}px`;
div.style.height = `${document.documentElement.clientHeight}px`;
div.style.background = `url(${canvas.toDataURL( "image/png" )}) left top repeat`;
document.body.appendChild(div);
}
setOptions({fontSize = 18, width = 300, height = 300, opacity = 1, str = "" }) {
this .fontSize = fontSize;
this .width = width;
this .height = height;
this .fillStyle = fillStyle
this .opacity = opacity;
this .str = str;
this .draw();
}
// 绘制
render() {
this .draw();
window.onresize = () => {
this .draw();
};
}
// 移除水印
removeWatermark() {
if (document.getElementById( this .id) !== null ) {
document.body.removeChild(document.getElementById( this .id));
}
}
}
|
2、在页面种引入使用:
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
|
import watermarkClass from "@/libs/watermarkClass" ;
export default {
name: "App" ,
mounted: function () {
this .initWatermark()
},
methods: {
initWatermark() {
// 方法一
let watermark = new watermarkClass({
id: "watermarkID" ,
str: "紫藤萝-watermarkClass" ,
fontSize: 20,
width: 300,
height: 200,
fillStyle: "#dddddd" ,
opacity: 0.4,
});
watermark.render();
// 5秒后,清除水印
setTimeout(() => {
watermark.removeWatermark();
}, 5000);
}
},
};
|
以上就是vue 使用class创建和清除水印的示例代码的详细内容,更多关于vue 创建和清除水印的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/luoxuemei/p/14153790.html