• react 页面统一添加可换行水印


    1.组件

    const watermark = ({
      // 使用 ES6 的函数默认值方式设置参数的默认取值
      container = document.body,
      width = '250px',
      height = '160px',
      textAlign = 'left',
      textBaseline = 'bottom',
      font = '20px Microsoft Yahei',
      fillStyle = 'rgba(184, 184, 184, 0.4)',
      content = 'loading',
      content2 = 'time',
      rotate = '10',
      zIndex = 1000
    } = {}, ...res) => {
    const args = res
    const canvas = document.createElement('canvas')
    
    canvas.setAttribute('width', width)
    canvas.setAttribute('height', height)
    const ctx = canvas.getContext('2d')
    
    ctx.textAlign = textAlign
    ctx.textBaseline = textBaseline
    ctx.font = font
    ctx.fillStyle = fillStyle
    ctx.rotate(Math.PI / 180 * rotate)
    // ctx.fillText(content, 30, parseFloat(height) / 2)
    ctx.fillText(content, 35, 15)
    ctx.fillText(content2, 10, 40)
    const base64Url = canvas.toDataURL()
    const __wm = document.querySelector('.__wm')
    const watermarkDiv = __wm || document.createElement('div')
    const styleStr = `
    position:absolute;
    top:0;
    left:0;
    100%;
    height:100%;
    z-index:${zIndex};
    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)
    }
    
    const MutationObserver = window.MutationObserver || window.WebKitMutationObserver
    if (MutationObserver) {
    let mo = new MutationObserver(function () {
    const __wm = document.querySelector('.__wm')
    console.log(__wm)
    // 只在__wm元素变动才重新调用 __canvasWM
    if ((__wm && __wm.getAttribute('style') !== styleStr) || !__wm) {
    // 避免一直触发
    mo.disconnect()
    mo = null
    watermark(JSON.parse(JSON.stringify(args)))
    }
    })
    
    mo.observe(container, {
    attributes: true,
    subtree: true,
    childList: true
    })
    }
    
    }
    
    export default watermark
    

    2.入口文件引入

    import watermark from './utils/watermark'
    
    
    watermark({
      content: ‘水印内容’,
      container: document.querySelector('#root')
    })
    

      

  • 相关阅读:
    BZOJ 3611: [Heoi2014]大工程 [虚树 DP]
    BZOJ 3991: [SDOI2015]寻宝游戏 [虚树 树链的并 set]
    BZOJ 2286: [Sdoi2011消耗战 [DP 虚树]
    BZOJ 4767: 两双手 [DP 组合数]
    BZOJ 1426: 收集邮票 [DP 期望 平方]
    转「服务器运维」如何解决服务器I/O过高的问题
    iostat查看linux硬盘IO性能
    Linux前台、后台、挂起、退出、查看命令汇总
    Linux虚拟内存的作用
    -bash: iostat: command not found解决办法
  • 原文地址:https://www.cnblogs.com/feng3037/p/14028780.html
Copyright © 2020-2023  润新知