在网上找了个图片添加文字水印的案列,现在我想把文字水印添加到图片的中间或者右下倾斜,望大神解答。希望把代码写出来,写在哪里需要注意什么!谢谢
// html img
<img class="sample2" data-img2blob="../../img/nan/m103.941.11/M103 (1).jpg" alt="">
// 页面JS
<script src="../../js/jquery-1.12.4.min.js" type="text/javascript"></script>
<script src="../../js/img2blob.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// default
$(".sample1").img2blob();
// with watermark
$(".sample2").img2blob({
watermark: '水印 水印 水印',
fontStyle: 'Microsoft YaHei,Arial',
fontSize: '45', // px
fontColor: 'yellow', // default 'black'
font: 40, // The x coordinate where to start painting the text
fontY: 60, // The y coordinate where to start painting the text
});
});
</script>
// img2blob.js
$.fn.img2blob = function(a) {
var b = {
watermark: '',
fontStyle: 'Arial',
fontSize: '30',
fontColor: 'black',
fontX: 10,
fontY: 50,
};
if (typeof a === 'object') {
a.watermark = (a.watermark == undefined ? b.watermark : a.watermark);
a.fontStyle = (a.fontStyle == undefined ? b.fontStyle : a.fontStyle);
a.fontSize = (a.fontSize == undefined ? b.fontSize : a.fontSize);
a.fontColor = (a.fontColor == undefined ? b.fontColor : a.fontColor);
a.fontX = (a.fontX == undefined ? b.fontX : a.fontX);
a.fontY = (a.fontY == undefined ? b.fontY : a.fontY);
} else {
a = b;
}
$(this).each(function(i, c) {
var d = $(this).data('img2blob'),
e = '.' + $(this).attr('class'),
f = new Image();
f.onload = function() {
var g = document.createElement('canvas');
g.width = f.naturalWidth;
g.height = f.naturalHeight;
var h = g.getContext('2d');
h.drawImage(f, 0, 0);
if(a.watermark != ''){
h.font = a.fontSize + 'px ' + a.fontStyle;
h.fillStyle = a.fontColor;
h.fillText(a.watermark, a.fontX, a.fontY);
}
var j = g.toDataURL('image/png'),
k = DataUriToBinary(j),
l = new Blob([k], {
type: 'image/png'
}),
m = window.URL.createObjectURL(l);
$(e).eq(i).attr('src', m);
};
f.src = d;
});
function DataUriToBinary(n) {
var o = ';base64,',
p = n.indexOf(o) + o.length,
q = n.substring(p),
r = window.atob(q),
s = r.length,
t = new Uint8Array(new ArrayBuffer(s));
for (i = 0; i < s; i++) {
t[i] = r.charCodeAt(i);
}
return t;
}
}
代码出处 https://hovertree.com/h/bjag/kfq30wnj.htm