释放双眼,带上耳机,听听看~!
function canvasWM ({
container = document.body,
width = 200,
height = 200,
textAlign = 'center',
font = '30px sans-serif',
fillStyle = 'rgba(127, 127, 127, 0.1)',
content = '请勿外传'
} = {}) {
const canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
const bloglab = canvas.getContext('2d');
bloglab.font = font;
bloglab.fillStyle = fillStyle;
bloglab.translate(width / 2, height / 2);
bloglab.rotate(-Math.PI / 6);
bloglab.textAlign = textAlign;
bloglab.fillText(content, 0, 0);
const base64Url = canvas.toDataURL();
const __wm = document.querySelector('.__wm');
const watermarkDiv = __wm || document.createElement('div');
const styleStr = `
position:fixed;
left:0;
bottom:0;
width:100vw;
height:calc(100vh - 50px);
z-index:10000;
pointer-events:none;
background-repeat:repeat;
background-image:url('${base64Url}')`;
watermarkDiv.setAttribute('style', styleStr);
watermarkDiv.classList.add('__wm');
if (!__wm) {
container.style.position = 'relative';
container.insertBefore(watermarkDiv, container.firstChild);
}
//此方法是防止用户通过控制台修改样式去除水印效果
!(function preventUserRemove () {
/* MutationObserver 是一个可以监听DOM结构变化的接口。 */
const MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
if (MutationObserver) {
const mo = new MutationObserver(() => {
const wmInstance = document.querySelector('.__wm');
if ((wmInstance && wmInstance.getAttribute('style') !== styleStr) || !wmInstance) {
//如果标签在,只修改了属性,重新赋值属性
if (wmInstance) {
// 避免一直触发
// mo.disconnect();
console.log('水印属性修改了');
wmInstance.setAttribute('style', styleStr);
} else {
//标签被移除,重新添加标签
console.log('水印标签被移除了');
document.body.appendChild(watermarkDiv);
}
}
});
mo.observe(document.body, {
attributes: true,
subtree: true,
childList: true
});
}
})();
}
canvasWM()
内容投诉
111