在生活中我们到处都可以见到带有水印的文档。网上也到处可见的水印图片,如csdn,淘宝,百度上的图片都带有水印。
尤其是现在盗版非常严重的社会。你刚写的文章,几秒钟后就出现在其他网站上,然后就会出现,到底谁是原创问题。如何解决盗版问题,其他的方法之一就是图片添加水印,让盗文章的人没有立足之地。
运行效果如下:

全部源代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<title>使用Canvas给图片添加水印</title>
</head>
<body>
<canvas id="xttblog" width="500" height="200"></canvas>
<br/><input value="www.xttblog.com" id="test"/><br/>
<input value="重新生成水印" type="button" onclick="watermark(document.getElementById('test').value);"/>
<script>
function watermark(url) {
canvas = document.getElementById("xttblog");
if (canvas.getContext){
ctx = canvas.getContext('2d');
var img1 = new Image();
img1.src='xttblog.bmp';
img1.onload = function(){
var imgWidth=img1.width;
var imgHeight=img1.height;
canvas.width= imgWidth;
canvas.height=imgHeight;
ctx.drawImage(img1,0,0);
// 创建渐变
var gradient=ctx.createLinearGradient(0,0,canvas.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
// 用渐变填色
ctx.fillStyle = gradient;
// 水印字体
ctx.font = '30px Verdana';
// 水印
ctx.fillText(url, canvas.width-450,canvas.height-100);
}
}
}
watermark('www.xttblog.com');
</script>
</body>
</html>

: » 使用Canvas给图片添加水印
原创文章,作者:端木书台,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/251127.html