在网页中给图片添加水印,既能保护版权也能标注来源。HTML本身不直接提供水印属性,但配合CSS、canvas或SVG可以轻松实现。下面介绍三种常用的HTML图片水印添加方法。

一、使用CSS定位叠加水印
这是最简单的方法,通过外层容器相对定位,水印层绝对定位覆盖在图片上方。适合固定文字或logo水印。
<div class="img-box">
<img src="https://picsum.photos/400/300?random=2" alt="原图" />
<span class="watermark">ipipp.com</span>
</div>
<style>
.img-box {
position: relative;
display: inline-block;
}
.img-box .watermark {
position: absolute;
right: 10px;
bottom: 10px;
color: rgba(255, 255, 255, 0.6);
font-size: 14px;
pointer-events: none;
}
</style>
这种方法的优点是代码少,但水印是独立DOM节点,用户可通过开发者工具删除。
二、使用canvas生成带水印的图片
canvas可以把文字或图片直接绘制到图像像素上,导出为新图,水印更难被剥离。
function addWatermark(imgSrc, text) {
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.font = '20px sans-serif';
ctx.fillText(text, canvas.width - 120, canvas.height - 20);
document.body.appendChild(canvas);
};
img.src = imgSrc;
}
addWatermark('https://picsum.photos/400/300?random=3', 'ipipp.com');
注意如果图片跨域,需服务器允许或改用同域图片,否则canvas会污染无法读取。
三、使用SVG实现矢量水印
SVG水印放大不失真,可将<svg>作为背景或直接嵌入。下面用SVG文本做平铺水印背景。
<div class="svg-wm">
<img src="https://picsum.photos/400/300?random=4" alt="图" />
</div>
<style>
.svg-wm {
position: relative;
}
.svg-wm::after {
content: "";
position: absolute;
inset: 0;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><text x='10' y='50' font-size='12' fill='rgba(0,0,0,0.2)'>ipipp.com</text></svg>");
}
</style>
SVG方式兼顾清晰度和样式灵活,是响应式页面的不错选择。
总结
以上三种HTML图片水印添加方法各有优劣:CSS快捷但易被删,canvas安全但稍重,SVG清晰可缩放。实际项目中可组合使用,提升图片保护效果。