使用canvas给页面添加水印
提示:此处使用原生javaScript写法,也可在vue项目中使用
前言
提示:记录和分享项目中比较有意思的点,同时为了方便他人
一、效果展示
二、项目源码
1.js方法
const watermarkFun = (item) => {
// 唯一id
const id = '3.1415926.2346712'
if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id))
}
// 使用canvas, 绘制水印
const str = item
const canvasEle = document.createElement('canvas')
canvasEle.width = 230
canvasEle.height = 180
const ctx = canvasEle.getContext('2d')
ctx.rotate(-25 * Math.PI / 180)
ctx.font = '16px serif'
ctx.fillStyle = 'rgba(200, 200, 200, 0.8)'
ctx.textAlign = 'left'
ctx.fillText(str, canvasEle.width / 16, canvasEle.height / 2)
// 把canvas转化为图片背景图,添加到div
const divEle = document.createElement('div')
divEle.id = id
divEle.style.width = document.documentElement.clientWidth + 'px'
divEle.style.height = document.documentElement.clientHeight + 'px'
divEle.style.pointerEvents = 'none'
divEle.style.position = 'fixed'
divEle.style.top = '5px'
divEle.style.left = '0px'
divEle.style.background = 'url(' + canvasEle.toDataURL() + ') left top repeat'
divEle.style.zIndex = 999999
// 把div添加到body根节点
document.body.appendChild(divEle)
return id
}
// 设置水印
watermarkFun('公司内部文件禁止外传')
// 监听页面缩放事件,重绘
window.onresize = () => {
watermarkFun('公司内部文件禁止外传')
}
2.完整案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
const watermarkFun = (item) => {
// 唯一id
const id = '3.1415926.2346712'
if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id))
}
// 使用canvas, 绘制水印
const str = item
const canvasEle = document.createElement('canvas')
canvasEle.width = 230
canvasEle.height = 180
const ctx = canvasEle.getContext('2d')
ctx.rotate(-25 * Math.PI / 180)
ctx.font = '16px serif'
ctx.fillStyle = 'rgba(200, 200, 200, 0.8)'
ctx.textAlign = 'left'
ctx.fillText(str, canvasEle.width / 16, canvasEle.height / 2)
// 把canvas转化为图片背景图,添加到div
const divEle = document.createElement('div')
divEle.id = id
divEle.style.width = document.documentElement.clientWidth + 'px'
divEle.style.height = document.documentElement.clientHeight + 'px'
divEle.style.pointerEvents = 'none'
divEle.style.position = 'fixed'
divEle.style.top = '5px'
divEle.style.left = '0px'
divEle.style.background = 'url(' + canvasEle.toDataURL() + ') left top repeat'
divEle.style.zIndex = 999999
// 把div添加到body根节点
document.body.appendChild(divEle)
return id
}
// 设置水印
watermarkFun('公司内部文件禁止外传')
// 监听页面缩放事件,重绘
window.onresize = () => {
watermarkFun('公司内部文件禁止外传')
}
</script>
</html>
总结
干货博主,欢迎点赞和收藏,支持原创作者;如果您觉得文章有改进的地方,欢迎私聊博主!