js实现给html加水印

发布时间:2023年12月18日

创建一个 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')
文章来源:https://blog.csdn.net/weixin_45791806/article/details/135057584
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。