<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body id="waterWrapper"> <canvas id="canvas"></canvas> <script> function drawWaterPrint(){ const canvas = document.getElementById('canvas'); canvas.width = 200; canvas.height = 200; canvas.style.display = 'none'; const ctx = canvas.getContext('2d'); ctx.font ='16px Microsoft JhengHei'; ctx.fillStyle ='rgba(0,0,0,.3)'; ctx.rotate(-0.3) ; ctx.fillText('大东在路上',canvas.width / 8,canvas.height / 4); // ctx.fillText('大东在路上',20,20); const img = canvas.toDataURL('image/png' ) const style =`background-image:url(${img})` if(style !== waterWrapper.style){ waterWrapper.setAttribute( 'style',style); } } drawWaterPrint() function callback(){ drawWaterPrint() } const observer = new MutationObserver(callback) const targetNode = waterWrapper // 监听节点 const config = {attributes : true} // 监听属性 observer.observe(targetNode,config) </script> </body> </html>
标签:canvas,const,ctx,style,水印,drawWaterPrint,功能,waterWrapper From: https://www.cnblogs.com/zhuangdd/p/17282775.html