|
| 1 | +import React, { useEffect, useState } from 'react'; |
| 2 | + |
| 3 | +interface WatermarkProps { |
| 4 | + text: string; |
| 5 | + fontSize?: number; |
| 6 | + fontFamily?: string; |
| 7 | + textColor?: string; |
| 8 | + rotate?: number; |
| 9 | + zIndex?: number; |
| 10 | + theme?: 'light' | 'dark'; |
| 11 | +} |
| 12 | + |
| 13 | +const Watermark: React.FC<WatermarkProps> = ({ |
| 14 | + text, |
| 15 | + fontSize = 16, |
| 16 | + fontFamily = 'Arial', |
| 17 | + textColor = 'rgba(0, 0, 0, 0.1)', |
| 18 | + rotate = -45, |
| 19 | + zIndex = 9999, |
| 20 | + theme = 'light', |
| 21 | +}) => { |
| 22 | + const [watermarkUrl, setWatermarkUrl] = useState<string>(''); |
| 23 | + |
| 24 | + useEffect(() => { |
| 25 | + const canvas = document.createElement('canvas'); |
| 26 | + const context = canvas.getContext('2d'); |
| 27 | + |
| 28 | + if (context) { |
| 29 | + const scale = window.devicePixelRatio; |
| 30 | + canvas.width = 300 * scale; |
| 31 | + canvas.height = 150 * scale; |
| 32 | + context.scale(scale, scale); |
| 33 | + |
| 34 | + context.font = `${fontSize}px ${fontFamily}`; |
| 35 | + context.fillStyle = theme === 'light' ? textColor : 'rgba(255, 255, 255, 0.1)'; |
| 36 | + context.rotate((rotate * Math.PI) / 180); |
| 37 | + context.fillText(text, 0, 100); |
| 38 | + |
| 39 | + setWatermarkUrl(canvas.toDataURL()); |
| 40 | + } |
| 41 | + }, [text, fontSize, fontFamily, textColor, rotate, theme]); |
| 42 | + |
| 43 | + return ( |
| 44 | + <div |
| 45 | + style={{ |
| 46 | + position: 'fixed', |
| 47 | + top: 0, |
| 48 | + left: 0, |
| 49 | + width: '100%', |
| 50 | + height: '100%', |
| 51 | + zIndex, |
| 52 | + pointerEvents: 'none', |
| 53 | + backgroundImage: `url(${watermarkUrl})`, |
| 54 | + backgroundRepeat: 'repeat', |
| 55 | + }} |
| 56 | + /> |
| 57 | + ); |
| 58 | +}; |
| 59 | + |
| 60 | +export default Watermark; |
0 commit comments