优化HTML2Canvas的输出 [英] Optimize output of HTML2Canvas

查看:761
本文介绍了优化HTML2Canvas的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 amchart 创建了一个图表.稍后我将不得不将其导出为PDF.
由于建议在此处,我需要进行转换首先使用 html2canvas 将图表插入SVG.

I created a chart with amchart. I will later have to export it as PDF.
As suggested here, I need to convert the chart first into SVG with html2canvas.

它可以工作,但是图表看起来坏了":

It works, but the chart looks "broken":

有什么方法可以优化结果?

Is there any way to optimize the result?

这是我的代码的一部分:

Here is an extract of my code:

   /* --- Chart --- */

var chart = AmCharts.makeChart("chartdiv1", {
  "type": "serial",
  // ...
});

/* --- HTML2Canvas --- */

$('#cmd').click(function() {
  html2canvas($("#output"), {
    onrendered: function(canvas) {
      document.body.appendChild(canvas);
    }
  });
})

这是一个小提琴.

PS:我知道,每个图表都有一个内置的导出功能.我无法使用它的原因是,在实际情况下,将要导出更多内容(几个图表,表格,文本等),因此我需要导出整个DIV.

推荐答案

我尝试了同样的方法,并通过更改SVG宽度和高度来解决此问题.这是用于解决此问题的代码.

I have tried the same, and fix this by changing the SVG width and height. Here is the code used to fix the issue.

function printOptions(type = 'before') {
    var svg = chart.div.querySelector('svg');
    if (svg) {
       if (type == 'after') { // remove the attributes after generating canvas
          svg.removeAttribute('width');
          svg.removeAttribute('height');
       } else { // set width and height according to parent container
          svg.setAttribute('width', chart.div.clientWidth);
          svg.setAttribute('height', chart.div.clientHeight);
       }
       chart.validateNow(); // validating am chart again.
     }
}    
// code for download image
downloadImage() {
   printOptions();
   html2canvas(document.getElementById('chart-div')).then(canvas => {
      printOptions('after');
      let a = document.createElement('a');
      a.href = canvas.toDataURL("image/png")
      a.download = 'Report.png';
      a.click();
    });
 }

工作演示 ,您可以在转换图像之前对printOption进行注释导出的图像更改.

Working Demo, you can comment printOption before converting the image for the exported image changes.

这篇关于优化HTML2Canvas的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆