创建一个 dom 元素调用下面的方法
var setWatermark = (str,dom) => {
const id = '23.12.18';
const element = document.getElementById(id);
if (element !== null) {
element.parentNode.removeChild(element); // 从其父节点中移除该元素
}
const oBOM = document.getElementById(dom);
const width = oBOM.offsetWidth || document.documentElement.clientWidth;
const height = oBOM.offsetHeight || document.documentElement.clientHeight;
oBOM.style.position = 'relative';
oBOM.style.overflow = 'hidden';
const can = document.createElement('canvas');
can.width = 200;
can.height = 130;
const cans = can.getContext('2d');
cans.rotate((-20 * Math.PI) / 180);
cans.font = '12px Vedana';
cans.fillStyle = 'rgba(200, 200, 200, 0.40)';
cans.textBaseline = 'Middle';
cans.fillText(str, can.width / 10, can.height / 2);
const div = document.createElement('div');
div.id = id;
div.style.pointerEvents = 'none';
div.style.top = '15px';
div.style.left = '0px';
div.style.position = 'absolute';
div.style.top = 0;
div.style.left = 0;
div.style.zIndex = '10000000';
div.style.width = `100%`;
div.style.height = `${height}px`;
div.style.background = `url(${can.toDataURL('image/png')}) left top repeat`;
oBOM.appendChild(div);
return id;
};
比如:
<div id="watermark">
<div style="width:300px;height:300px;background-color: red; opacity:0.98;">test</div>
<div style="width:300px;height:300px;background-color: blue; opacity:0.9;">test</div>
</div>
调用:
setWatermark('asdad','watermark')