给项目加水印是一个极其普遍的需求,下面就分2种方法用几行代码搞定!
方法一:非canvas实现
/**
* @description: createWaterMark.js 加水印功能
*/
let waterMarkDOM;
let clearWaterMark = () => {
if (waterMarkDOM) waterMarkDOM.remove();
};
/**
* @description: 创建水印
* @param {String} contentText 水印内容
*/
export default function createWaterMark(waterMarkName) {
clearWaterMark();
if (!waterMarkName) {
return;
}
let width = window.parseInt(document.body.clientWidth);
let canvasWidth = width / window.parseInt(width / 320);
let fontFamily = window.getComputedStyle(document.body)['font-family'];
const fragment = document.createDocumentFragment();
waterMarkDOM = document.createElement('div');
waterMarkDOM.className = 'water-mark-wrap';
let spanStr = '';
for (let i = 0; i < 100; i++) {
spanStr += `<span class="water-word" style=width:${canvasWidth}px;height:200px;font: ${fontFamily}>${waterMarkName}</span>`;
}
waterMarkDOM.innerHTML = spanStr;
fragment.appendChild(waterMarkDOM);
document.body.appendChild(fragment);
}
在App.vue文件中加上相关样式并且调用就大功告成啦~
import WaterMark from '文件路径/waterMark.js';
.....
mounted() {
WaterMark('这是水印');
}
<style>
.water-mark-wrap {
position: absolute;
width: 100%;
height: 100%;
z-index: 9999;
pointer-events: none;
top: 0;
left: 0;
display: flex;
overflow: hidden;
flex-wrap: wrap;
}
.water-word {
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
color: rgba(8, 8, 8, 0.1);
transform: rotate(-45deg);
user-select: none;
}
</style>
方法二:使用canvas
let style;
let clearWaterMark = () => {
if (style) style.remove();
};
export default function createWaterMark(userName) {
clearWaterMark();
if (!userName) {
return;
}
let width = window.parseInt(document.body.clientWidth);
let canvasWidth = width / window.parseInt(width / 320);
let fontFamily = window.getComputedStyle(document.body)["font-family"];
let canvas = document.createElement("canvas");
canvas.width = canvasWidth;
canvas.height = 200;
let ctx = canvas.getContext("2d");
ctx.rotate((-20 * Math.PI) / 180);
ctx.font = `18px ${fontFamily}`;
ctx.fillStyle = "rgba(8,8,8,.1)";
ctx.fillText(userName, 50, 200);
let imgSrc = canvas.toDataURL("image/png");
style = document.createElement("style");
style.innerHTML = `.with-watermark:before{
content: "";
width: 100%;
height: 100%;
display: block;
position: absolute;
z-index: -1;
background-image: url("${imgSrc}");
}`;
(document.head.append || document.head.appendChild).apply(document.head, [style]);
}
调用,在App.vue中,引入文件,并加上类名: with-watermark
,然后调用方法传入水印显示的内容即可
<template>
<div id="app" class="with-watermark"></div>
</template>
import WaterMark from '文件路径/waterMark.js';
mounted() {
waterMark("这是水印");
}