React Hook 實現水印效果

import React, {useEffect, useState} from 'react'
import {observer} from 'mobx-react-lite'


const WaterMark = ({text = '', option}) => {
  const {
    top = '0px',
    left = '0px',
    width,
    height,
  } = option

  const [background, setBackground] = useState('')
  

  useEffect(() => {
    const can = document.createElement('canvas')
    // 設置畫布的長寬
    can.width = option.w || 380
    can.height = option.h || 200
  
    const cans = can.getContext('2d')
    // 旋轉角度
    cans.rotate(-15 * Math.PI / 180)
    cans.font = '18px Vedana'
    // 設置填充繪畫的顏色、漸變或者模式
    cans.fillStyle = 'rgba(200, 200, 200, 0.40)'
    // 設置文本內容的當前對齊方式
    cans.textAlign = 'left'
    // 設置在繪製文本時使用的當前文本基線
    cans.textBaseline = 'Middle'
    // 在畫布上繪製填色的文本(輸出的文本,開始繪製文本的X座標位置,開始繪製文本的Y座標位置)
    cans.fillText(text, can.width / 8, can.height / 2)

    setBackground(`url(${can.toDataURL('image/png')}) left top repeat`)
  }, [text])

  return <div 
    className="noevent pa testttttt"
    style={{
      top,
      left,
      width,
      height,
      background,
      zIndex: 999,
    }}
  />
}


export default observer(WaterMark)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章