前端实现水印的几种方式

实现方式水印的实现方式有很多,根据实现功能的人员分工可以分为前端水印和后端水印,前端水印的优点可以总结为三点,第一,可以不占用服务器资源,完全依赖客户端的计算能力,减少服务端压力 。第二,速度快,无论哪种前端的实现方式,性能都是优于后端的 。第三,实现方式简单 。后端实现水印的最大优势也可以总结为三点,就是安全,安全,安全 。知乎,微博都是采用后端实现的水印方案 。但是综合考虑,我们还是采用前端实现水印的方案 。下面也会简单介绍下 nodejs 怎么实现后端图片水印 。
node实现提供三个 npm 包,本部分不是我们文章的重点,只提供简单的 demo 。1,gm https://github.com/aheckmann/gm 6.4k star
const fs = require('fs');const gm = require('gm');gm('/path/to/my/img.jpg').drawText(30, 20, "GMagick!").write("/path/to/drawing.png", function (err) {if (!err) console.log('done');});需要安装 GraphicsMagick 或者 ImageMagick;2,node-images:https://github.com/zhangyuanwei/node-images
var images = require("images");images("input.jpg")//Load image from file//加载图像文件.size(400)//Geometric scaling the image to 400 pixels width//等比缩放图像到400像素宽.draw(images("logo.png"), 10, 10)//Drawn logo at coordinates (10,10)//在(10,10)处绘制Logo.save("output.jpg", {//Save the image to a file, with the quality of 50quality : 50//保存图片到文件,图片质量为50});不需要安装其他工具,轻量级,zhangyuanwei 国人开发,中文文档;3,jimp:https://github.com/oliver-moran/jimp可搭配 gifwrap 实现 gif 水印;
前端实现1,背景图实现全屏水印
可以到阿里内外个人信息页面查看效果,原理:

前端实现水印的几种方式

文章插图
【前端实现水印的几种方式】 
优点:图片是后端生成,安全;缺点:需要发起 http 请求,获取图片信息;效果展示:由于是内部系统,不方便展示效果 。
2,dom 实现全图水印和图片水印
在图片的 onload 事件里获取图片宽高,根据图片大小生成水印区域,遮挡在图片上层,dom 内容为水印的文案或者其他信息,实现方式比较简单 。
const wrap = document.querySelector('#ReactApp');const { clientWidth, clientHeight } = wrap;const waterHeight = 120;const waterWidth = 180;// 计算个数const [columns, rows] = [~~(clientWidth / waterWidth), ~~(clientHeight / waterHeight)]for (let i = 0; i < columns; i++) {for (let j = 0; j <= rows; j++) {const waterDom = document.createElement('div');// 动态设置偏移值waterDom.setAttribute('style', `width: ${waterWidth}px;height: ${waterHeight}px;left: ${waterWidth + (i - 1) * waterWidth + 10}px;top: ${waterHeight + (j - 1) * waterHeight + 10}px;color: #000;position: absolute`);waterDom.innerText = '测试水印';wrap.appendChild(waterDom);}}优点:简单易实现;缺点:图片过大或者过多会有性能影响;效果展示:
前端实现水印的几种方式

文章插图
 
3,canvas 实现方式(第一版实现方案)方法一:直接在图片上操作
废话不多说,直接上代码
useEffect(() => {// gif 图不支持if (src && src.includes('.gif')) {setShowImg(true);}image.onload = function () {try {// 太小的图不加载水印if (image.width < 10) {setIsDataError(true);props.setIsDataError && props.setIsDataError(true);return;}const canvas = canvasRef.current;canvas.width = image.width;canvas.height = image.height;// 设置水印const font = `${Math.min(Math.max(Math.floor(innerCanvas.width / 14), 14), 48)}px` || fontSize;innerContext.font = `${font} ${fontFamily}`;innerContext.textBaseline = 'hanging';innerContext.rotate(rotate * Math.PI / 180);innerContext.lineWidth = lineWidth;innerContext.strokeStyle = strokeStyle;innerContext.strokeText(text, 0, innerCanvas.height / 4 * 3);innerContext.fillStyle = fillStyle;innerContext.fillText(text, 0, innerCanvas.height / 4 * 3);const context = canvas.getContext('2d');context.drawImage(this, 0, 0);context.rect(0, 0, image.width || 200, image.height || 200);// 设置水印浮层const pattern = context.createPattern(innerCanvas, 'repeat');context.fillStyle = pattern;context.fill();} catch (err) {console.info(err);setShowImg(true);}};image.onerror = function () {setShowImg(true);};}, [src]);优点:纯前端实现方式,右键复制的图片也是有水印的;缺点:不支持 gif,图片必须支持跨域;效果展示:下文给出 。
方法二:canvas 生成水印 url 赋值给 css background 属性


推荐阅读