当我们浏览网页查看图片的时候,经常看到图片上会有水印出现。有时我们需要在图片上加水印用来标示归属或者其他信息,怎么实现呢,这里就要用到我们的 canvas-画布。
实现思路 :图片加载成功后画到canvas中,随后在canvas中绘制水印,完成后通过canvas.toDataUrl()方法获得base64并替换原来的图片路径。
话不多说,上代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<div id="box" onclick="alert(o)">
<img />
</div>
</body>
<script>
(function() {
function ImgX({
url = '',
textAlign = 'center',
textBaseline = 'middle',
fillStyle = 'rgba(180, 180, 180, 0.7)',
content = '水印',
ele = null,
textX = 90,
textY = 30
} = {}) {
const img = new Image();
img.src = url;
img.crossOrigin = 'anonymous';
img.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const obj = canvas.getContext('2d');
obj.drawImage(img, 0, 0);
obj.textAlign = textAlign;
obj.textBaseline = textBaseline;
obj.fillStyle = fillStyle;
obj.fillText(content, img.width - textX, img.height - textY);
const base64Url = canvas.toDataURL();
ele && ele(base64Url);
}
}
if (typeof module != 'undefined' && module.exports) {
module.exports = ImgX;
} else if (typeof define == 'function' && define.amd) {
define(function () {
return ImgX;
});
} else {
window.ImgX = ImgX;
}
})();
// 调用
ImgX({
url: './1.jpg',
content: '水印',
ele: (base64Url) => {
document.querySelector('img').src = base64Url
},
});
</script>
</html>
以上。
欢迎交流。