一、问题背景
为了防止信息泄露或知识产权被侵犯,在web的世界里,对于页面和图片等增加水印处理是十分有必要的,水印的添加根据环境可以分为两大类,前端浏览器环境添加和后端服务环境添加,简单对比一下这两种方式的特点:
前端浏览器加水印:
减轻服务端的压力,快速反应
适用场景:资源为某个用户独有,一份原始资源只需要做一次处理,将其存储之后就无需再次处理,水印的目的在于标示资源的归属人 这里我们讨论前端浏览器环境添加
import watermark from '@/utils/watermark.js';
watermark.set('张三1234567890')
// 取消水印
watermark.out()
watermark.js
'use strict'
let watermark = {
}
let setWatermark = (str) => {
let id = '1.23452384164.123412415'
if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id))
}
let can = document.createElement('canvas')
can.width = 350
can.height = 250
let cans = can.getContext('2d')
cans.rotate(-15 * Math.PI / 150)
cans.font = '20px Vedana'
cans.fillStyle = 'rgba(200, 200, 200, 0.50)'
cans.textAlign = 'left'
cans.textBaseline = 'Middle'
cans.fillText(str, can.width / 16, can.height / 2)
let div = document.createElement('div')
div.id = id
div.style.pointerEvents = 'none'
div.style.top = '100px'
div.style.left = '0px'
div.style.position = 'fixed'
div.style.zIndex = '100000'
div.style.width = document.documentElement.clientWidth + 'px'
div.style.height = document.documentElement.clientHeight + 'px'
div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
document.body.appendChild(div)
return id
}
// 该方法只允许调用一次
watermark.set = (str) => {
let id = setWatermark(str)
setInterval(() => {
if (document.getElementById(id) === null) {
id = setWatermark(str)
}
}, 500)
window.onresize = () => {
setWatermark(str)
}
}
const outWatermark = (id) => {
if (document.getElementById(id) !== null) {
const div = document.getElementById(id)
div.style.display = 'none'
}
}
watermark.out = () => {
const str = '1.23452384164.123412415'
outWatermark(str)
}
export default watermark