react網頁新增水印(轉)
阿新 • • 發佈:2020-11-12
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 Yaheiwatermark({ content:projectTit+'-'+loginId+'-'+loginTime, container:document.querySelector('#watermark') }) 公司前幾天有這個需求,親測可用,謝謝大佬!', 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; width: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