关注前端开发
关注用户体验

canvas小tip–下载二维码、图片加水印

    昨天介绍了一个生成二维码的插件QRCode.js,它是借助HTML5 Canvas绘制而成。所以,今天的主角就是canvas啦–canvas的实际应用。

    一、下载二维码(查看如何生成二维码

    HTMLCanvasElement提供了toDataURL方法,该方法返回一个包含被类型参数规定图像表现格式的data URI。通过该方法我们就可以生成二维码图片并下载了。示例如下:

/*html*/
<div id="qrcode">div>
<a href="javascript:;" download="二维码" id="down">下载二维码</a>

/*js*/
var canvas = document.getElementsByTagName('canvas')[0];
var downImg = document.getElementById('down')
img.href = document.getElementsByTagName('canvas')[0].toDataURL('image/png')

    二、图片加水印

    利用canvas的fillText和drawImage方法可以轻松实现给图片加水印(水印的细节可自行设置)。示例如下:

/*html*/
<canvas id="canvas"></canvas>

/*js*/
var img = new Image();   // 创建img元素
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d');
img.src = 'myImage.png';

img.onload = function(){
ctx.drawImage(img, 0, 0);
  ctx.font="30px yahei"; //设置水印文字
  ctx.fillText("大前端", 1100, 260)
}

    今天暂时写到这里,欢迎分享关于canvas的其他应用。

 

赞(179)
未经允许不得转载:大前端 » canvas小tip–下载二维码、图片加水印
分享到: 更多 (0)

评论 5

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #5

    Woh I like your articles , saved to fav! .

    Nonton Anime1个月前 (05-11)回复
  2. #4

    This would be the proper weblog for wants to find out about this topic. You realize a great deal its nearly hard to argue on hand (not too When i would want…HaHa). You actually put a brand new spin with a topic thats been discussing for a long time. Wonderful stuff, just fantastic!

    cat blog1个月前 (05-08)回复
  3. #3

    I am curious to find out what blog platform you happen to be working with? I’m experiencing some minor security problems with my latest blog and I would like to find something more secure. Do you have any recommendations?

    my singing monsters3个月前 (03-28)回复
  4. #2

    Rattling excellent info can be found on web blog .

    Garfield Boldul3个月前 (03-11)回复
  5. #1

    1好

    12211个月前 (07-25)回复

themebetter 国内更好的WordPress主题服务商

立即前往