1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| export const drawWaterMark = function (content = '水印') { const container = document.body; const width = '300'; const height = '200'; const textAlign = 'center'; const textBaseline = 'middle'; const font = '16px Microsoft Yahei'; const fillStyle = 'rgba(184, 184, 184, 0.2)'; const rotate = '30'; const zIndex = 10000;
const canvas = document.createElement('canvas');
canvas.setAttribute('width', `${width}px`); canvas.setAttribute('height', `${height}px`); 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, parseFloat(width) / 2, parseFloat(height) / 4);
const base64Url = canvas.toDataURL(); const watermarkDiv = document.createElement('div'); const styleStr = ` position:fixed; top:0; left:0; bottom:0; right: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('watermark');
container.insertBefore(watermarkDiv, container.firstChild);
const observer = new MutationObserver(() => { const wmInstance = document.querySelector('.watermark'); console.log('MutationObserver'); if ((wmInstance && wmInstance.getAttribute('style') !== styleStr) || !wmInstance) { if (wmInstance) { wmInstance.setAttribute('style', styleStr); } else { container.insertBefore(watermarkDiv, container.firstChild); } } });
observer.observe(container, { attributes: false, subtree: false, childList: true, }); observer.observe(document.querySelector('.watermark'), { attributes: true, subtree: true, childList: true, }); };
|