Java基础、中级、高级、架构面试资料

使用Canvas给图片添加水印

HTML5 herman 3754浏览 0评论
公告:“业余草”微信公众号提供免费CSDN下载服务(只下Java资源),关注业余草微信公众号,添加作者微信:xttblog2,发送下载链接帮助你免费下载!
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
视频教程免费领
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云

在生活中我们到处都可以见到带有水印的文档。网上也到处可见的水印图片,如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>

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!

本文原文出处:业余草: » 使用Canvas给图片添加水印