/** * 生成水印函数 * * @category Utils */ export function __canvasWM({ container = document.querySelector('.wm-container'), width = '300px', height = '200px', textAlign = 'center', textBaseline = 'middle', font = '18px Microsoft Yahei', fillStyle = 'rgba(255, 255, 255, 0.15)', content = '华锐分布式', rotate = -30, zIndex = 2000, } = {}) { const args = arguments[0]; const canvas = document.createElement('canvas'); canvas.setAttribute('width', width); canvas.setAttribute('height', height); const ctx: any = canvas.getContext('2d'); ctx.textAlign = textAlign; ctx.textBaseline = textBaseline; ctx.font = font; ctx.fillStyle = fillStyle; ctx.rotate((Math.PI / 180) * rotate); ctx.fillText(content, 0, (parseFloat(height) * 4) / 5); 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-image:url('${base64Url}')`; watermarkDiv.setAttribute('style', styleStr); watermarkDiv.classList.add('__wm'); if (!__wm) { container?.insertBefore(watermarkDiv, container.firstChild); } const MutationObserver = window.MutationObserver || (window as any).WebKitMutationObserver; if (MutationObserver) { // 针对div本身 let mo: MutationObserver | null = new MutationObserver(() => { const __wm = document.querySelector('.__wm'); // 只在__wm元素变动才重新调用 __canvasWM // 代码修改content会出现无限刷新的entity,stylesStr不一致 if ((__wm && __wm.getAttribute('style') !== styleStr) || !__wm) { // 避免一直触发 mo?.disconnect(); mo = null; __canvasWM(JSON.parse(JSON.stringify(args))); } }); mo.observe(watermarkDiv, { attributes: true, }); let parent: MutationObserver | null = new MutationObserver( (mutationRecords = []) => { mutationRecords.forEach(record => { let wmDiv = false; record.removedNodes.forEach((item: any) => { if (item.className === '__wm') { wmDiv = true; } }); if (wmDiv) { const __wm = document.querySelector('.__wm'); // 只在__wm元素变动才重新调用 __canvasWM if ((__wm && __wm.getAttribute('style') !== styleStr) || !__wm) { // 避免一直触发 parent?.disconnect(); parent = null; __canvasWM(JSON.parse(JSON.stringify(args))); } } }); }, ); if (container) { parent.observe(container, { childList: true, }); } } }