一、简介
HTML5 <canvas> 元素用于图形的绘制,通过脚本 (通常是JavaScript)来完成.
<canvas> 标签只是图形容器,您必须使用脚本来绘制图形。
你可以通过多种方法使用 canvas 绘制路径,盒、圆、字符以及添加图像。
二、如何构建画布、绘制图片、通过a标签进行下载
1.绘制画布
var canvas = document.createElement('canvas');
canvas.height = 1334;
canvas.width =750;
canvas.style.width = 750 + "px";
canvas.style.height = 1334 + "px";
2.创建 context 对象
var ctx = canvas.getContext('2d');
3.生成一张图片_img1
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src=("#downloadPoster1").attr('href', canvas.toDataURL("image/png")); //将画布转成图片路径赋值给a标签的href
var activityName = ('#downloadPoster1').attr("download", activityName);//给a标签添加download属性,属性值为下载的图片的名称
};
5.点击a标签下载绘制好的图片
6.图片跨域问题处理方法
a.创建图片的时候 img.crossOrigin = 'Anonymous';
b.在请求图片的时候添加请求头
image.png
三、整体代码
绘制图片
function canvasPosterImg(){
("#qrCodeImg").attr("style","width: 100%;height: auto;display: block");
("#qrCodePoster img").attr('src'));
//解决跨域,将跨域图片路径转为base64格式
var img = new Image();
var canvas = document.createElement('canvas');
canvas.height = 1334;
canvas.width =750;
canvas.style.width = 750 + "px";
canvas.style.height = 1334 + "px";
var ctx = canvas.getContext('2d');
img.crossOrigin = 'Anonymous';
img.src=("#downloadPoster1").attr('href', canvas.toDataURL("image/png"));
var activityName = ('#downloadPoster1').attr("download", activityName);
};
}
四、下载图片(使用压缩包的方式下载图片)
a.引入对应的工具包
<script src="/javascript/activity/js_zip/FileSaver.js"></script>
<script src="/javascript/activity/js_zip/jszip.min.js"></script>
/**
- 批量下载海报
*/
function brachDownLoadPoster(activitySharePageInfoList){
//获取渠道二维码的列表
//activitySharePageInfoList 为需要下载的图片列表的详情信息
if(activitySharePageInfoList == null || activitySharePageInfoList.length < 1){
.each(activitySharePageInfoList, function (i, shareInfo) {
var shareInfoId = shareInfo.id ;
var shareName = shareInfo.name;
var img = new Image();
var canvas = document.createElement('canvas');
canvas.height = 1334;
canvas.width =750;
canvas.style.width = 750 + "px";
canvas.style.height = 1334 + "px";
var ctx = canvas.getContext('2d');
img.crossOrigin = 'Anonymous';
img.src=('#qrCode'+shareInfoId+' img')[0];
ctx.drawImage(img2, QRleft1, QRtop1,QRwidth1,QRwidth1);
var url = canvas.toDataURL("image/png")
// 构造a标签并模拟点击
var imgData = url.split('base64,')[1];
zip.file(shareName+"图片.png", imgData , { base64:true });
if(zipNo==size ){
//下载压缩包
var activityName = ("#ma-Updata").modal('hide');
zipNo = 0;
});
}
};
})
}
网友评论