代码语言:javascript复制
import { debounce } from "./index"
const id = 'water-mark'
const setWaterMark = (content) => {
if (document.getElementById(id) != null) document.body.removeChild(document.getElementById(id))
const canvas = document.createElement('canvas')
canvas.width = 300
canvas.height = 150
const ctx = canvas.getContext('2d')
ctx.rotate((-20 * Math.PI) / 180)
ctx.font = '14px normal'
ctx.fillStyle = 'rgba(200, 200, 200, 0.30)'
ctx.textBaseline = 'middle'
ctx.textAlign = 'center'
const contents = Array.isArray(content) ? content : [content]
contents.forEach((item, index) => {
ctx.fillText(item || "", canvas.width / 5, canvas.height / 2 (index * 20))
})
const dom = document.createElement('div')
dom.id = id
dom.style.pointerEvents = 'none'
dom.style.position = 'absolute'
dom.style.top = '0px'
dom.style.left = '0px'
dom.style.zIndex = '9'
dom.style.width = `${document.documentElement.clientWidth}px`
dom.style.height = `${document.documentElement.clientHeight}px`
dom.style.background = `url(${canvas.toDataURL('image/png')}) repeat`
document.body.appendChild(dom)
}
export default (content) => {
if (document.getElementById(id) == null) setWaterMark(content)
window.onresize = debounce(() => setWaterMark(content))
}
代码语言:javascript复制import waterMark from '@/utils/waterMark.js'
waterMark("添加水印")
// 或多个
waterMark(["添加水印","添加水印"])