最近工作中遇到的需求,将div转成图片并保存。
1、准备需要用到的js插件jquery-1.8.2.js,html2canvas.min.js(将div转换为canvas),bluebird.js(用户IE支持ES6Promise特性)
2、页面demo
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>divtoimgdemo</title>
<styletype="text/css">
.content{
display:block;
position:relative;
width:300px;
height:300px;
background-color:#E6B246
}
</style>
</head>
<body>
<divclass="content"id="imgDiv">
<div>测试</div>
</div>
<buttonid="btn">保存为图片</button>
</body>
</html>
3、遇到的问题
问题1:生成的图片模糊
解决方案:将canvas属性放大两倍,生成的时候再变回原来的1倍;
问题2:IE浏览器不支持ES6新特性,无法使用html2canvas插件生成画布
解决方案:引入bluebird.js,只需引入即可;
问题3:在执行保存时,如果直接使用html2canvas插件提供的,将生成的画布直接转换为base64的方法,将base64直接放到a标签的href属性中进行下载,当生成图片内容过多时,base64长度将超出a标签href长度限制,无法下载。
解决方案:将base64转换为Blob流
问题4:有些浏览器,比如火狐,不支持a标签直接下载
解决方案:还是使用Blob流下载
最终代码:
<scripttype="text/javascript">
$(document).ready(function(){
//canvas生成图片
$("#btn").on("click",function(){
vargetPixelRatio=function(context){//获取设备的PixelRatio
varbackingStore=context.backingStorePixelRatio||
context.webkitBackingStorePixelRatio||
context.mozBackingStorePixelRatio||
context.msBackingStorePixelRatio||
context.oBackingStorePixelRatio||
context.backingStorePixelRatio||0.5;
return(window.devicePixelRatio||0.5)/backingStore;
};
//生成的图片名称
varimgName="cs.jpg";
varshareContent=document.getElementById("imgDiv");
varwidth=shareContent.offsetWidth;
varheight=shareContent.offsetHeight;
varcanvas=document.createElement("canvas");
varcontext=canvas.getContext('2d');
varscale=getPixelRatio(context);//将canvas的容器扩大PixelRatio倍,再将画布缩放,将图像放大PixelRatio倍。
canvas.width=width*scale;
canvas.height=height*scale;
canvas.style.width=width+'px';
canvas.style.height=height+'px';
context.scale(scale,scale);
varopts={
scale:scale,
canvas:canvas,
width:width,
height:height,
dpi:window.devicePixelRatio
};
html2canvas(shareContent,opts).then(function(canvas){
context.imageSmoothingEnabled=false;
context.webkitImageSmoothingEnabled=false;
context.msImageSmoothingEnabled=false;
context.imageSmoothingEnabled=false;
vardataUrl=canvas.toDataURL('image/jpeg',1.0);
dataURIToBlob(imgName,dataUrl,callback);
});
});
})
//editedfromhttps://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#Polyfill
vardataURIToBlob=function(imgName,dataURI,callback){
varbinStr=atob(dataURI.split(',')[1]),
len=binStr.length,
arr=newUint8Array(len);
for(vari=0;i<len;i++){
arr[i]=binStr.charCodeAt(i);
}
callback(imgName,newBlob([arr]));
}
varcallback=function(imgName,blob){
vartriggerDownload=$("<a>").attr("href",URL.createObjectURL(blob)).attr("download",imgName).appendTo("body").on("click",function(){
if(navigator.msSaveBlob){
returnnavigator.msSaveBlob(blob,imgName);
}
});
triggerDownload[0].click();
triggerDownload.remove();
};
</script>
demo下载:div_to_img_demo
如果您觉得本文的内容对您的学习有所帮助:
关键字:
jquery