zoukankan      html  css  js  c++  java
  • react网页添加水印(转)

    const watermark = ({
        // 使用 ES6 的函数默认值方式设置参数的默认取值
        // 具体参见 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Default_parameters
        container = document.body,
        width = '400px',
        height = '400px', 
        textAlign = 'left',
        textBaseline = 'bottom',
        font = '14px Microsoft Yahei',
        fillStyle = 'rgba(184, 184, 184, 0.4)',
        content = '',
        rotate = '24',
        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, 100, parseFloat(height) / 2) 
    // ctx.fillText(content, 20, parseFloat(height) / 2) 
    
    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
    watermark({
          content: projectTit+'-'+loginId+'-'+loginTime,
          container: document.querySelector('#watermark') 
        })
    公司前几天有这个需求,亲测可用,谢谢大佬!
  • 相关阅读:
    asp.net string有多行文字
    asp.net设置gridview页码显示遇到的问题
    asp.net button浏览器端事件和服务器端事件
    GridView 控制默认分页页码间距 及字体大小
    复合主键与联合主键(转载)
    vsCode 列选择、列选中、选中列、选中多列(转载)
    可能有用的技术社区(转载)
    SQL 用于各种数据库的数据类型(转载) sqlserver 数据类型 取值范围 长度
    TypeError: value.getTime is not a function (elementUI报错转载 )
    工作1年3个月总结(201707-201810 )
  • 原文地址:https://www.cnblogs.com/snowhite/p/13963909.html
Copyright © 2011-2022 走看看