2 种实现图片加水印的方式
来源 | http://www.fly63.com/
安全系数较低,对于掌握一定前端知识的人来说可以通过各种骚操作跳过水印获取到源文件
适用场景:资源不跟某一个单独的用户绑定,而是一份资源,多个用户查看,需要在每一个用户查看的时候添加用户特有的水印,多用于某些机密文档或者展示机密信息的页面,水印的目的在于文档外流的时候可以追究到责任人
安全性高,无法获取到加水印前的源文件
适用场景:资源为某个用户独有,一份原始资源只需要做一次处理,将其存储之后就无需再次处理,水印的目的在于标示资源的归属人
1、canvas 生成方式
export default class CanvasWay {constructor(watermark) {this.watermark = watermarkconst {width, height} = watermarkthis.canvas = document.createElement('canvas');this.canvas.setAttribute('width', width);this.canvas.setAttribute('height', height);}render() {const {txt, x, y, width, height, font, color, fontSize, alpha, angle} = this.watermarkconst ctx = this.canvas.getContext('2d');ctx.clearRect(0, 0, width, height);ctx.textBaseline = 'top';ctx.textAlign = 'left'ctx.fillStyle = color;ctx.globalAlpha = alpha;ctx.font = `${fontSize}px ${font}`ctx.translate(x, y)ctx.rotate(Math.PI / 180 * angle);ctx.translate(-x, -y - fontSize)ctx.fillText(txt, x, y + fontSize);return this.canvas.toDataURL();}}
2、svg 生成方式
export default class SvgWay {constructor(watermark) {this.watermark = watermark}render() {const {txt, x, y, width, height, color, font, fontSize, alpha, angle} = this.watermarkconst svgStr =`<svg xmlns="http://www.w3.org/2000/svg" width="${width}px" height="${height}px"><text x="${x}px" y="${y}px" dy="${fontSize}px"text-anchor="start"stroke="${color}"stroke-opacity="${alpha}"fill="none"transform="rotate(${angle},${x} ${y})"font-weight="100"font-size="${fontSize}"font-family="${font}">${txt}</text></svg>`;return `data:image/svg+xml;base64,${window.btoa(unescape(encodeURIComponent(svgStr)))}`;}}
总结
逆锋起笔是一个专注于程序员圈子的技术平台,你可以收获最新技术动态、最新内测资格、BAT等大厂的经验、精品学习资料、职业路线、副业思维,微信搜索逆锋起笔关注!
学习更多技能
请点击下方公众号 


评论
