vue 使用class创建和清除水印的示例代码
(编辑:jimmy 日期: 2024/11/24 浏览:3 次 )
页面添加水印的方法有很多,以下举例使用class定义的方法进行水印内容渲染:
1、新建文件:WatermarkClass.js
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、在页面种引入使用:
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 创建和清除水印的资料请关注其它相关文章!
下一篇:React中使用Vditor自定义图片详解