react实现页面水印效果的全过程

目录

  • 前言
  • 1.使用示例
  • 2.实现过程
  • 3.组件代码
  • 总结

前言 1.为什么选用svg 而不是cavans?
因为cavans 在高分辨率屏幕下,需要根据 devicePixelRatio做宽高的适配,不然就会很模糊,而svg是矢量图,原生支持各种分辨率,不会产生模糊的情况。

1.使用示例
import React from 'react'import ReactDOM from 'react-dom'import './index.css'import WaterMarkContent from './components/WaterMarkContent'import App from './App'ReactDOM.render(,document.getElementById('root'))

react实现页面水印效果的全过程
文章图片


2.实现过程
  • 构造一个水印图
  • 将水印图铺满整个容器
  • 水印组件:支持子组件内容插槽
构造一个svg 的水印图
const { text = 'waterMark', fontSize = 16, fillOpacity = '0.2', fillColor = '#000' } = propsconst res = ` ${text}`

由上面的代码,我们可以得到一个svg xml 的字符串,接下来我们将它变成url 资源
const blob = new Blob([res], {type: 'image/svg+xml',}) const url = URL.createObjectURL(blob)

由此,我们就得到了一个svg 的资源地址,现在我们将它用于div 的背景图当中

至此,我们很轻松的得到了一个铺满水印的div,下面我们将代码整合,并封装成组件。

3.组件代码
import React from 'react'import { ReactNode, useMemo } from 'react'type svgPropsType = {text?: stringfontSize?: numberfillOpacity?: numberfillColor?: string}const SvgTextBg = (props: svgPropsType) => {const { text = 'waterMark', fontSize = 16, fillOpacity = '0.2', fillColor = '#000' } = propsconst res = ` ${text}`const blob = new Blob([res], {type: 'image/svg+xml',})const url = URL.createObjectURL(blob)return ()}type propsType = {children?: ReactNode} & Partialconst WaterMarkContent = (props: propsType) => {const { text, fontSize, fillOpacity, fillColor } = propsconst memoInfo = useMemo(() => ({text,fontSize,fillOpacity,fillColor,}),[text, fontSize, fillOpacity, fillColor])return ({props.children})}export default WaterMarkContent


总结 【react实现页面水印效果的全过程】到此这篇关于react实现页面水印效果的文章就介绍到这了,更多相关react实现页面水印内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读