react 實(shí)現(xiàn)水印功能

背景:在后臺管理的項(xiàng)目中,會要求加上水印,防止截圖盜取信息等,

1. 第一步:先創(chuàng)建水印的模塊組件

// water-maker.tsx

import React ,{ memo, useMemo } from "react"
import styles from './index.less';
import { renderToString } from "react-dom/server";
const Index = (props: React.PropsWithChildren<{text:string ,fillColor?:string,fillOpacity?:number , fontSize?:number}>) => {

 const svgUrl= useMemo(() => {
   const svgRes =  (<svg xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="300px" height="180px" viewBox="0 0 300 180">
     <text x="-160" y="-30" fill={props.fillColor ||'#333'} transform="rotate(-35 220 -220)" fill-opacity={props.fillOpacity  ||'0.1'}
       font-size={`${props.fontSize||'28'}px`}> {props.text}</text>
   </svg>)
   return URL.createObjectURL(new Blob([renderToString(svgRes)], {
     type:'image/svg+xml',
   }))
 }, [props]);
 
 return (<div className={styles.waterMaker}
   style={{ backgroundImage: `url(${svgUrl})` }}
 >
   {props.children}
 </div>)

}

export default memo(Index)

// index.less
.waterMaker{
 position: absolute;
 width: 100%;
 height: 100%;
 pointer-events: none;
 top: 0;
 left: 0;
 z-index: 999;
}

創(chuàng)建一個(gè)svg的標(biāo)簽,里面畫上自己需要的水印內(nèi)容,然后生成通過URL.createObjectURL生成一個(gè)url鏈接作為模塊的背景;通過 pointer-events: none;這個(gè)屬性可以將點(diǎn)擊事件透傳到下層。

2. 使用水印組件作用于項(xiàng)目的app.tsx上

  <React.StrictMode>
    <App />
    <WaterMaker text='水印哈哈哈'  />
  </React.StrictMode>

展示圖片.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容