搜索引擎找不到的网站,国外app模板下载网站,企业年金个人查询官网,室内设计工作室在 Vue 项目中添加水印可以通过以下几种方式实现#xff1a; 方法一#xff1a;使用 CSS
直接通过 CSS 的 background 属性实现水印#xff1a;
实现步骤
在需要添加水印的容器中设置背景。使用 rgba 设置透明度#xff0c;并通过 background-repeat 和 background-size…在 Vue 项目中添加水印可以通过以下几种方式实现 方法一使用 CSS
直接通过 CSS 的 background 属性实现水印
实现步骤
在需要添加水印的容器中设置背景。使用 rgba 设置透明度并通过 background-repeat 和 background-size 实现重复。
示例代码
templatediv classwatermark-containerp这是带水印的内容。/p/div
/templatestyle
.watermark-container {position: relative;width: 100%;height: 200px;background-color: #f0f0f0;background-image: url(data:image/svgxml;utf8,svg xmlnshttp://www.w3.org/2000/svg width200 height200text x20 y100 font-size20 fillrgba(0,0,0,0.2) transformrotate(-45)Watermark/text/svg);background-repeat: repeat;
}
/style方法二通过 Canvas 动态生成水印
使用 Canvas 动态生成水印并将其作为背景图应用。
实现步骤
在 Vue 中创建一个方法通过 canvas 动态生成水印图。将生成的图像作为背景图应用到需要添加水印的元素上。
示例代码
templatediv classwatermark-container :style{ backgroundImage: watermark }p这是带水印的内容。/p/div
/templatescript
export default {data() {return {watermark: ,};},mounted() {this.generateWatermark();},methods: {generateWatermark() {const canvas document.createElement(canvas);const ctx canvas.getContext(2d);canvas.width 200;canvas.height 200;ctx.font 20px Arial;ctx.fillStyle rgba(0, 0, 0, 0.2);ctx.textAlign center;ctx.textBaseline middle;ctx.translate(100, 100);ctx.rotate((-45 * Math.PI) / 180);ctx.fillText(Watermark, 0, 0);this.watermark url(${canvas.toDataURL(image/png)});},},
};
/scriptstyle
.watermark-container {position: relative;width: 100%;height: 200px;background-repeat: repeat;
}
/style方法三封装水印组件
如果需要复用可以封装一个通用的水印组件。
示例代码
templatediv classwatermark :style{ backgroundImage: watermark }slot/slot/div
/templatescript
export default {props: {text: {type: String,default: Watermark,},fontSize: {type: String,default: 20px,},color: {type: String,default: rgba(0, 0, 0, 0.2),},rotate: {type: Number,default: -45,},},data() {return {watermark: ,};},mounted() {this.generateWatermark();},methods: {generateWatermark() {const canvas document.createElement(canvas);const ctx canvas.getContext(2d);canvas.width 200;canvas.height 200;ctx.font ${this.fontSize} Arial;ctx.fillStyle this.color;ctx.textAlign center;ctx.textBaseline middle;ctx.translate(100, 100);ctx.rotate((this.rotate * Math.PI) / 180);ctx.fillText(this.text, 0, 0);this.watermark url(${canvas.toDataURL(image/png)});},},
};
/scriptstyle
.watermark {position: relative;width: 100%;height: 100%;background-repeat: repeat;
}
/style使用
templatedivWatermark textConfidential colorrgba(255,0,0,0.1)p这是机密内容。/p/Watermark/div
/templatescript
import Watermark from ./Watermark.vue;export default {components: {Watermark,},
};
/script以上方法可以根据需求选择适合的方式实现水印效果。