js 实现图片水印
使用Canvas实现图片水印
通过Canvas绘制水印并叠加到原图上,适用于前端动态生成水印场景。
function addWatermark(imageUrl, text, options = {}) {
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = imageUrl;
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.font = options.font || '20px Arial';
ctx.fillStyle = options.color || 'rgba(255, 255, 255, 0.5)';
ctx.textAlign = options.align || 'center';
ctx.textBaseline = options.baseline || 'middle';
ctx.fillText(text, img.width/2, img.height/2);
const watermarkedImage = canvas.toDataURL('image/png');
return watermarkedImage;
};
}
CSS背景水印方案
通过CSS重复平铺半透明文本作为背景,适合网页内容保护。
.watermarked {
position: relative;
}
.watermarked:after {
content: "CONFIDENTIAL";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
color: rgba(0, 0, 0, 0.3);
transform: rotate(-45deg);
pointer-events: none;
}
SVG动态水印生成
利用SVG创建可缩放的水印图案,保持清晰度不受分辨率影响。
function createSvgWatermark(text) {
const svg = `
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<text x="50%" y="50%"
font-family="Arial"
font-size="20"
fill="rgba(0,0,0,0.1)"
text-anchor="middle"
dominant-baseline="middle"
transform="rotate(-45 100 100)">
${text}
</text>
</svg>
`;
return `url('data:image/svg+xml;utf8,${encodeURIComponent(svg)}')`;
}
透明PNG水印叠加
预先制作透明PNG水印图片,通过绝对定位叠加到目标图片上。
<div style="position: relative; display: inline-block;">
<img src="original.jpg" alt="Original Image">
<img src="watermark.png"
style="position: absolute;
top: 0;
left: 0;
opacity: 0.5;
pointer-events: none;">
</div>
批量处理图片水印
使用File API处理用户上传的多个图片文件并添加水印。
function batchWatermark(files, text) {
const results = [];
Array.from(files).forEach(file => {
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
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.font = '24px Arial';
ctx.fillStyle = 'rgba(255,255,255,0.7)';
ctx.fillText(text, 30, 30);
canvas.toBlob(blob => {
results.push(new File([blob], `watermarked_${file.name}`));
}, 'image/jpeg');
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
return results;
}






