源码
/**
* 给页面打水印
*
*
* 参数介绍:
* message: 显示水印的文字;
* {
* font: 水印字体大小,样式,如:16px sans-serif
* color: 水印字体颜色,如:#ccc
* };
* dom元素,非必填,不填的情况下为body;
*/
function createWaterMark (
message,
{
font, color, position, width, height, angleCount, globalAlpha, zIndex} = {
},
dom = document.body) {
const WIDTH = width || 160
const HEIGHT = height || 160
const canvas = document.createElement('canvas')
canvas.width = WIDTH
canvas.height = HEIGHT
const ctx = canvas.getContext('2d')
if (!ctx) {
return
}
ctx.font = font || '16px sans-serif'
ctx.fillStyle = color || '#7f7f7f'
ctx.globalAlpha = globalAlpha || 0.1
ctx.translate(WIDTH / 2, HEIGHT / 2)
ctx.rotate(-Math.PI / (angleCount || 6))
ctx.textAlign = 'center'
ctx.fillText(message || '', 0, 0)
const dataURL = canvas.toDataURL('image/png')
const mask = document.createElement('div')
mask.style.width = '100%'
mask.style.height = '100%'
mask.style.position = position || 'fixed'
mask.style.left = '0'
mask.style.top = '0'
if (_.isNumber(zIndex)) {
mask.style.zIndex = String(zIndex)
} else {
mask.style.zIndex = '10000'
}
mask.style.pointerEvents = 'none'
mask.style.backgroundImage = `url(${
dataURL})`
dom.append(mask)
}
export default createWaterMark
水印插件使用方法
// 引入
import createWaterMark from '@/plugins/water-mark'
createWaterMark(
'developer', //打水印的内容
{
position: 'absolute', //水印样式
color: '#333',
font: '30px sans-serif',
width: 400,
height: 300,
angleCount: 8,
globalAlpha: 0.1
},
document.getElementById('xxxx') //被打水印的Dom, 非必填,不填的情况下为body
)
//简易使用方法
createWaterMark(
'developer', //打水印的内容
{
color: '#333',
font: '30px sans-serif'
})
页面效果: