给网页添加全屏水印,而且不影响页面原有的点击事件。
页面中运行这个方法即可:
function watermark(){
var name = '水印内容文字';
var opacity = 0.2; // 水印透明度
var w = 100; // 水印宽度
var h = 200; // 水印高度
var genWater = function(name) {
var waterCanvas = document.createElement('canvas');
waterCanvas.id = 'water-canvas';
waterCanvas.setAttribute('width', w);
waterCanvas.setAttribute('height', h);
var ctx = waterCanvas.getContext('2d');
ctx.rotate(Math.PI / 180 * 30);
ctx.font = '15px serif';
ctx.fillText(name, 10, 10);
var base64Url = waterCanvas.toDataURL();
var waterMarkDiv = document.createElement('div');
var styleStr = 'position:absolute;top:0;left:0;width:100%;height:100%;z-index:99999;pointer-events:none;background-image:url(' + base64Url + ');opacity: ' + opacity + ';';
waterMarkDiv.setAttribute('style', styleStr);
waterMarkDiv.classList.add('__wm');
return waterMarkDiv;
};
var container = document.body;
var waterMarkDiv = genWater(name);
container.insertBefore(waterMarkDiv, container.firstChild);
var callback = function(record) {
for (var i = 0; i < record.length; i++) {
var item = record[i];
var target = item.target;
if (target.nodeType === 1) {
var removedNodes = item.removedNodes;
if (target.nodeName === 'BODY' && removedNodes.length > 0) {
for (var j = 0; j < removedNodes.length; j++) {
var element = removedNodes[j];
if (element.nodeType === 1 && element.nodeName === 'DIV' && element.classList.contains('__wm')) {
waterMarkDiv = genWater(name);
container.insertBefore(waterMarkDiv, container.firstChild);
}
}
}
var type = item.type;
if (target.nodeName === 'DIV' && target.classList.contains('__wm') && type === 'attributes') {
container.removeChild(waterMarkDiv);
}
}
}
};
if (typeof MutationObserver === 'function') {
var obs = new MutationObserver(callback);
var options = {
childList: true,
attributes: true,
subtree: true,
characterData: true
};
obs.observe(container, options);
}
}
原理:
新建画布,用水印文字绘制在画布中;
新建一个div,将画布作为背景色填充到div里面平铺,并设置透明度;
将div放在页面最外层,占满整个页面。
设置div关键css 属性pointer-events:none; 保证不影响页面上原来的点击事件;