Created
April 11, 2015 09:41
-
-
Save think2011/70a408dd2a675ce1bcb8 to your computer and use it in GitHub Desktop.
给图片加水印
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 给图片打文字水印 | |
* @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