利用canvas做页面背景渲染在div盒子里,然后把div盒子挂载到body上实现水印覆盖
1、获取用户信息,当做水印文本
async function getUserInfo() {
//根据项目获取
}
2、初始化水印字体相关配置
config.fontSize=12;//字体大小
config.rotate=45; //字体旋转角度
config.gap=0; //水印间距
config.opacity=0.1 ;//水印透明度
3、根据水印角度计算水印宽高
function getWidthAndHeight(config) {
const ctx = document.createElement('canvas').getContext('2d');
ctx.font = config.fontSize 'px sans-serif';
const strLength = ctx.measureText(config.text).width 10 config.gap;
const width = Number(Math.cos(Math.PI / 180 config.rotate) * strLength).toFixed(0);
const height = Number(Math.sin(Math.PI / 180 config.rotate) * strLength).toFixed(0);
config.width = +width;
config.height = +height;
}
4、开始绘制画布
注意设置pointer-events: none,避免造成错误的鼠标点击事件
const canvas = document.createElement('canvas')
// 设置画布宽高
canvas.setAttribute('width', `${config.width}px`)
canvas.setAttribute('height', `${config.height}px`)
// 2d画板
const ctx = canvas.getContext('2d')
// 背景图片内容居中
ctx.textAlign = 'center';
// 背景图文字大小
ctx.font = config.fontSize 'px sans-serif';
// 确保背景内容在图片正中心
ctx.translate(config.width/2, config.height/2);
// 设置水印旋转角度
ctx.rotate(-Math.PI / 180 config.rotate);
// 设置水印文字的颜色
ctx.fillStyle = '#DDDEE2'
// 填充文本
ctx.fillText(config.text, 0, 5);
// 将图片转换为b64格式
const bgImg = canvas.toDataURL();
// 绘制水印容器
const waterMaker = document.createElement('div');
// 关键属性:pointer-events: none; 设置盒子点击穿透
const styleStr = `position: absolute; top: 0; left: 0; z-index: 999999; width: 100%; height: 100%; opacity: ${config.opacity}; pointer-events: none; background-repeat: repeat; background-image: url('${bgImg}');`;
waterMaker.setAttribute('style', styleStr);
// 类名保证在创建时只能有一层水印
waterMaker.className = 'highly-water-marker';
5、挂载到body
document.body.appendChild();
6、在系统初始化时引用