PC前端加水印

利用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、在系统初始化时引用

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值