Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

为什么a.download有时候下载的图片是空白,有时候有内容?

<script>
 var a = document.createElement('a');
 //setTimeout(generatePIC(),300)
 function generatePIC() {
          var svgXml = $('.svg-wrap').html();
 var image = new Image();
 image.src = 'data:image/svg+xml;base64,'+ window.btoa(unescape(encodeURIComponent(svgXml))); //给图片对象写入base64编码的svg流
 var canvas = document.createElement('canvas'); //准备空画布
 canvas.width = $('.svg-wrap svg').width();
 canvas.height =$('.svg-wrap svg').height();
 var context = canvas.getContext('2d'); //取得画布的2d绘图上下文
 //context.fillStyle = "#fff";//让导出的jpeg文件背景为白色,否则为黑色 //context.fillRect(0, 0, canvas.width, canvas.height);//让导出的jpeg文件背景为白色,否则为黑色 context.drawImage(image, 0, 0);
 a.href = canvas.toDataURL('image/png'); //将画布内的信息导出为png图片数据
 a.download = "MapByMathArtSys"; //设定下载名称
 a.click();
 a.remove();
 }
</script>

我的要求是点击一个按钮触发generatePIC函数,然后把class="svg-wrap"的div块里的SVG导出成图片下载,但是点击按钮时发现,虽然每次都能生成文件,但是往往最初点击按钮生成的文件是空白,后面的图片文件有内容。浏览器是chrome和Edge


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Image对象有一个方法。onload,这是图片加载完成后的事件方法。你这写法是同步的,下面的代码执行的时候可能图片还没有加载完成。后面的方法可以定义在onload事件方法里


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...