html2canvas把div保存图片高清图的方法示例
程序员文章站
2023-11-16 16:34:04
这篇文章主要介绍了html2canvas把div保存图片高清图的方法示例的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧... 18-03-05...
本文介绍了html2canvas把div保存图片高清图的方法示例,分享给大家,具体如下:
(可以搜索html2canvans)
1.选择html2canvas版本(这个版本可以放大倍数保证图片清晰)
默认生成的 canvas 图片在 retina 设备上显示很模糊,处理成 2 倍图能解决这个问题:
var w = $("#code").width(); var h = $("#code").height(); //要将 canvas 的宽高设置成容器宽高的 2 倍 var canvas = document.createelement("canvas"); canvas.width = w * 2; canvas.height = h * 2; canvas.style.width = w + "px"; canvas.style.height = h + "px"; var context = canvas.getcontext("2d"); //然后将画布缩放,将图像放大两倍画到画布上 context.scale(2,2); html2canvas(document.queryselector("#code"), { canvas: canvas, onrendered: function(canvas) { ... } });
下载方法:
.on('click','.download',function(){ $('#mycanvas').remove(); var _height=$('.skinreport').height(); //滚到顶部 $('html, body').animate({scrolltop:0}); if(confirm('是否下载肌肤检测报告?')) { settimeout(function(){ var canvas = document.createelement("canvas"), w=$('#skinreport').width(), h=$('#skinreport').height(); canvas.width = w * 2; canvas.height = h * 2; canvas.style.width = w + "px"; canvas.style.height = h + "px"; var context = canvas.getcontext("2d"); //然后将画布缩放,将图像放大两倍画到画布上 context.scale(2,2); html2canvas(document.getelementbyid('skinreport'), { allowtaint: false, tainttest: true, canvas: canvas, onrendered: function(canvas) { canvas.id = "mycanvas"; canvas.style.display = 'none'; document.body.appendchild(canvas); //生成base64图片数据 imgdata = canvas.todataurl(type); //var newimg = document.createelement("img"); //newimg.src = dataurl; //document.body.appendchild(newimg); //console.log(imgdata); 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'); /** * 在本地进行文件保存 * @param {string} data 要保存到本地的图片数据 * @param {string} filename 文件名 */ 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 = aname+'肌肤检测报告' + (new date()).gettime() + '.' + type; // download savefile(imgdata,filename); }, width:1512, height:15000 }) },2500) } else { return; } })
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。