2 種實現(xiàn)圖片加水印的方式
來源 | http://www.fly63.com/
安全系數(shù)較低,對于掌握一定前端知識的人來說可以通過各種騷操作跳過水印獲取到源文件
適用場景:資源不跟某一個單獨的用戶綁定,而是一份資源,多個用戶查看,需要在每一個用戶查看的時候添加用戶特有的水印,多用于某些機密文檔或者展示機密信息的頁面,水印的目的在于文檔外流的時候可以追究到責任人
安全性高,無法獲取到加水印前的源文件
適用場景:資源為某個用戶獨有,一份原始資源只需要做一次處理,將其存儲之后就無需再次處理,水印的目的在于標示資源的歸屬人
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)))}`;}}
總結(jié)
逆鋒起筆是一個專注于程序員圈子的技術(shù)平臺,你可以收獲最新技術(shù)動態(tài)、最新內(nèi)測資格、BAT等大廠的經(jīng)驗、精品學習資料、職業(yè)路線、副業(yè)思維,微信搜索逆鋒起筆關(guān)注!
學習更多技能
請點擊下方公眾號 


評論
圖片
表情
