网店系统H5版(五) 给商品图片添加二维码水印并下载

2020-4-5 21:32:41 星期日

网店需要提供分享并下载商品图片的功能, 这里使用jquery-qrcode + h5的canvas实现这个功能

并没有请求后端, 全是在客户端浏览器上执行的

用到的js库

 1 function createShareImage(goodsId, goodsImgUrl) {
 2     let urlGoodsDetail = location.origin + '/vstore_goodsinfo_' + goodsId; //商品详情页链接
 3     let urlGoodsImg = location.origin + goodsImgUrl; //商品图片链接
 4 
 5     let image = new Image();
 6     image.onload = function () {
 7         //创建画布
 8         let canvasElement = document.getElementById('goodsCanvas'); //已有或者通过 createElement 实时创建
 9         let ctx = canvasElement.getContext('2d');
10 
11         //将图片画到canvas上去
12         let imageW = image.width;
13         let imageH = image.height;
14         let w = imageW;
15         let h = imageH;
16         let maxWidth = 500;
17         if (imageW > maxWidth) {
18             w = maxWidth;
19             h = parseInt((maxWidth * imageH) / imageW);
20         }
21         canvasElement.setAttribute('width', w+'px');
22         canvasElement.setAttribute('height', h+'px');
23         ctx.drawImage(image, 0, 0, w, h);
24 
25         //生成商品二维码
26         $('#goodsQR').qrcode({text:urlGoodsDetail,quiet:2}); //需要引入jquery-qrcode
27         let canvasQR = document.getElementById('goodsQR').getElementsByTagName('canvas')[0];
28 
29         //将二维码画上去
30         let qrWidth = 80;
31         ctx.drawImage(canvasQR, w-qrWidth, h-qrWidth, qrWidth, qrWidth);
32 
33         //下载图片
34         let MIME_TYPE = "image/png";
35         let imgURL = canvasElement.toDataURL(MIME_TYPE);
36         let dlLink = document.createElement('a');
37         dlLink.download = goodsId.substring(0,10)+'.png';
38         dlLink.href = imgURL;
39         dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
40 
41         document.body.appendChild(dlLink);
42         dlLink.click();
43         document.body.removeChild(dlLink);
44     };
45 
46     image.src = urlGoodsImg;
47 }

 源码(码云)

posted @ 2020-04-05 21:38  myD  阅读(487)  评论(0编辑  收藏  举报