html:
http://www.w3school.com.cn/tiy/t.asp?f=html_a_download
a标签中加上属性href: 下载链接,download: 文件名称,如果download不设置文件后缀,则默认为href中本来的格式,如果download设置了文件后缀,则弹出框中会自动变成你设置的那个后缀,下面的代码,另存为框中默认为png格式。
<a href="imgname.gif" download="givenimgname.png">
<input type="button" value="下载">
</a>
将dom转变为canvas:
http://www.voidcn.com/blog/u013038861/article/p-6085659.html
http://blog.csdn.net/apeng_1102/article/details/50740436
<script type="text/javascript">
$(function(){
print();
});
function print(){
html2canvas( $("#canv") ,{
onrendered: function(canvas){ //这样做,DOM发生变化的不能保存
$('#down_button').attr( 'href' , canvas.toDataURL() ) ;
$('#down_button').attr( 'download' , 'name.png' ) ;
}
});
}
</script>
<script type="text/javascript" >
$(document).ready( function(){
$("#down_button").on("click", function(event) {
event.preventDefault();
html2canvas($("targrtDOM"), {
allowTaint: true,
taintTest: false,
onrendered: function(canvas) {
var dataUrl = canvas.toDataURL(); //生成base64图片数据,dataUrl就是下载链接
}
});
});
});
</script>
将canvas保存为图片:
http://www.uedsc.com/javascript-download-canvas.html
//通过toDataURL方法提取到canvas的base64编码数据
var type = 'png';
var imgData = document.getElementById(‘myCanvas’).toDataURL(type);
//mime-type改为image/octet-stream
var _fixType = function(type) {
type = type.toLowerCase().replace(/jpg/i, 'jpeg');
var r = type.match(/png|jpeg|bmp|gif/)[0];
return 'image/' + r;
};
// 加工image data,替换mime type
imgData = imgData.replace(_fixType(type),'image/octet-stream');
//保存
var saveFile = function(data, filename){
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = data;
save_link.download = filename;
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
};
// 下载后的文件名
var filename = 'qianzhui_' + (new Date()).getTime() + '.' + type;
// download
saveFile(imgData,filename);
网友评论