Skip to content

Instantly share code, notes, and snippets.

@think2011
Created April 11, 2015 09:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think2011/70a408dd2a675ce1bcb8 to your computer and use it in GitHub Desktop.
Save think2011/70a408dd2a675ce1bcb8 to your computer and use it in GitHub Desktop.
给图片加水印
/**
* 给图片打文字水印
* @param img Object||String
* @param opt
* @constructor
*/
function Watermark(img, opt) {
this.opt = opt;
if(typeof img === 'object') {
this.img = img;
} else {
this.img = document.createElement('img');
this.img.src = img;
}
}
Watermark.prototype = {
create: function(cb) {
var opt = this.opt,
img = this.img,
canvas = document.createElement("canvas");
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
ctx.font = opt.size + 'px Microsoft YaHei';
ctx.fillText(opt.text, opt.x, opt.y);
cb(canvas.toDataURL());
}
}
}
var wr = new Watermark('p.jpg', {
text: '水印测试成功,10010',
size: 18,
x: 100,
y: 282
});
var img = document.createElement('img');
wr.create(function (base64) {
img.src = base64;
document.body.appendChild(img);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment