一句话总结,动态创建canvas,绘制content,将HtmlCanvasElement使用toDataURL()方法,返回一个包含图片展示的data URI,最后创建一个div,设置background-image: url(canvasURI),平铺整个内容区
// 水印
export const waterMark = function ({
container = document.body,
width = '230px',
height = '180px',
textAlign = 'center',
textBaseline = 'middle',
font = '20px microsoft yahei',
fillStyle = 'rgba(184, 184, 184, 0.2)',
content = '请勿外传',
rotate = '30',
zIndex = 1000
} = {}) {
let canvas = document.createElement('canvas')
canvas.setAttribute('width', width)
canvas.setAttribute('height', height)
let ctx = canvas.getContext('2d')
ctx.textAlign = textAlign
ctx.textBaseline = textBaseline
ctx.font = font
ctx.fillStyle = fillStyle
ctx.rotate(Math.PI / 180 * rotate)
ctx.fillText(content, parseFloat(width) / 2, parseFloat(height) / 2)
let base64Url = canvas.toDataURL() // HTMLCanvasElement.toDataURL()方法返回一个包含图片展示的data URI
let waterMarkDiv = document.createElement('div')
waterMarkDiv.setAttribute('style', `
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: ${zIndex};
pointer-events: none;
background-repeat: repeat;
background-image: url('${base64Url}');
`)
container.style.position = 'relative;'
container.insertBefore(waterMarkDiv, container.firstChild)
}
使用:
waterMark({
container: document.getElementById('app'),
content: this.info.realName
})