watermark.js - 在浏览器中实现图片水印的利器
以下是一个简单的watermark.js
实现示例,用于在浏览器中给图片添加水印:
function Watermark({ text, font = '20px Arial', color = 'rgba(0, 0, 0, 0.5)' }) {
this.text = text;
this.font = font;
this.color = color;
}
Watermark.prototype.loadImage = function(src) {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = reject;
image.src = src;
});
};
Watermark.prototype.applyWatermark = async function(imageSrc) {
const image = await this.loadImage(imageSrc);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
ctx.font = this.font;
ctx.fillStyle = this.color;
ctx.textBaseline = 'bottom';
ctx.fillText(this.text, canvas.width - 10, canvas.height - 10);
return canvas.toDataURL();
};
// 使用示例
const watermarker = new Watermark({ text: '版权所有' });
watermarker.applyWatermark('path/to/your/image.jpg')
.then(watermarkedImageSrc => {
// 创建一个Image元素或者设置为背景图片等
const img = document.createElement('img');
img.src = watermarkedImageSrc;
document.body.appendChild(img);
})
.catch(error => {
console.error('An error occurred:', error);
});
这段代码定义了一个Watermark
类,它有两个方法:loadImage
用于异步加载图片,applyWatermark
将水印应用到图片上,并返回包含水印的图片的DataURL。使用时,只需创建一个Watermark
实例,并调用applyWatermark
方法,传入图片路径即可。
评论已关闭