document.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
document.addEventListener('webkitEnterFullscreen', function() {
document.body.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
});
document.addEventListener('mousedown', function(e) {
if (e.button === 0 && e.target.tagName.toLowerCase() === 'img') {
e.preventDefault();
}
});
const userInfo = {
mobile: '{$user["phone"]}',
nickname: '{$user["nickname"]}',
openid: '{$user["openid"]}'
};
function createWatermark({ mobile, nickname, openid }) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 设置画布尺寸
canvas.width = 400;
// canvas.height = 200;
canvas.height = 170;
// 绘制水印文本
ctx.font = '14px Arial';
ctx.fillStyle = '#666';
ctx.rotate(-20 * Math.PI / 180); // 旋转-20度
// 组合水印信息
// const text1 = `手机号:${mobile}`;
const text2 = `昵称:${nickname}`;
const text3 = `OpenID:${openid}`;
// ctx.fillText(text1, 40, 100);
ctx.fillText(text2, 40, 100);
ctx.fillText(text3, 40, 130);
return canvas.toDataURL('image/png');
}
// 创建水印层
function initWatermark() {
const watermarkDiv = document.createElement('div');
watermarkDiv.className = 'watermark';
// 生成背景图
const watermarkUrl = createWatermark(userInfo);
watermarkDiv.style.backgroundImage = `url(${watermarkUrl})`;
document.body.appendChild(watermarkDiv);
// 防篡改保护
observeWatermark(watermarkDiv);
}
// 防篡改监听(简易版)
function observeWatermark(element) {
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (!document.contains(element)) {
document.body.appendChild(element);
}
if (element.style.display === 'none') {
element.style.display = 'block';
}
});
});
observer.observe(document.body, {
childList: true,
attributes: true,
subtree: true
});
}
// 初始化
window.addEventListener('DOMContentLoaded', initWatermark);对应的css样式
.watermark {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none; /* 允许穿透操作 */
z-index: 9999;
opacity: 0.3;
background-repeat: repeat;
}相关文章