轮播图水印应采用Canvas动态绘制方案,需等待图片加载完成(onload)后执行,避免DOM重绘导致错位;服务端预处理适用于高敏场景,前端方案仅适用于权属声明。
直接在 标签上叠加 CSS 水印不可靠——轮播图切换时 DOM 重绘、缩放、懒加载都会让水印错位或消失。真正可控的方式是:用 canvas 绘制原图 + 水印文字/Logo,再把 canvas 输出为图片替换原图。
img.onload),否则 canvas 绘制为空白rgba(0,0,0,0.2))+ 白色描边,确保在亮图/暗图上都清晰img.naturalWidth 为 0function addWatermark(img, text = '© Company') {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
ctx.font = 'bold 16px sans-serif';
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.textAlign = 'right';
ctx.

textBaseline = 'bottom';
ctx.strokeText(text, canvas.width - 10, canvas.height - 10);
ctx.fillText(text, canvas.width - 10, canvas.height - 10);img.src = canvas.toDataURL('image/png');
}
// 示例:对轮播中所有 img 执行
document.querySelectorAll('.carousel img').forEach(img => {
if (img.complete) {
addWatermark(img);
} else {
img.addEventListener('load', () => addWatermark(img));
}
});
Swiper 的 onSlideChange 和 onImageLazyLoad 是加水印的关键时机。不能只在 mounted 里处理一次,因为懒加载图片、动态切换、loop 模式下会反复创建/销毁 img 元素。
swiper.on('lazyImageLoad', ...) 捕获每张懒加载完成的图useEffect 初始化 Swiper,需在 swiper?.on() 后手动清理监听器// Swiper 初始化片段(JS)
const swiper = new Swiper('.swiper', {
lazy: true,
on: {
lazyImageLoad: function (swiper, slide, img) {
addWatermark(img, this.params.watermarkText || 'Confidential');
}
}
});前端加水印有性能和绕过风险;敏感内容(如内部系统截图)必须服务端处理。Nginx 的 http_image_filter 模块可实时加文字水印,但仅支持简单位置和字体,且不支持透明度微调。
--with-http_image_filter_module
/slide-1.jpg?watermark=1
location ~* ^/slides/(.+)\.(jpe?g|png)$ {
image_filter resize 1200 -;
image_filter_jpeg_quality 95;
image_filter_transparency off;
# 注意:text_watermark 是自定义指令,标准模块不支持,需用 OpenResty + lua-resty-image
}只要图片资源能被浏览器下载,纯前端水印就可被截图或禁用 JS 后获取原图。真要防扩散,必须结合服务端策略:
oncontextmenu="return false" 完全无效Canvas 绘制的水印能挡住截图工具自动识别,但挡不住人工截屏——这点常被忽略。如果水印目的是“声明权属”而非“阻止复制”,当前方案已够用;如果目标是“防止信息泄露”,那就该换架构,而不是调字体透明度。