【问题标题】:Transforming SVG to CANVAS, PNG, and JPEG with c3.js使用 c3.js 将 SVG 转换为 CANVAS、PNG 和 JPEG
【发布时间】:2015-11-14 07:49:07
【问题描述】:

我正在尝试将 svg 图表转换为 png 和 jpeg 格式以下载图表。但是,我没有得到相同的图片。谁能告诉我为什么我会黑屏。任何帮助将不胜感激。谢谢

这是屏幕。

http://i.stack.imgur.com/0zdvX.pngscreen

【问题讨论】:

  • 似乎有些 CSS 没有应用。可能你有一些全局样式表,在转换时没有被使用。
  • 我该如何解决这个问题?我要添加哪个标记?
  • 要说明这一点,我们需要查看您当前的一些代码...

标签: canvas png jpeg c3.js


【解决方案1】:

我假设您正在使用 html2canvas http://html2canvas.hertzen.com 之类的库将 C3 SVG 转换为画布,然后转换为 PNG/JPEG

对于html2canvas,来自http://html2canvas.hertzen.com/documentation.html

因此,它只能正确渲染它的属性 理解,这意味着有许多 CSS 属性不起作用。

使用相同方法的其他库可能有类似的差距。


修正 C3.js + html2canvas 的黑色背景和粗线

假设您使用的是 html2canvas,以下代码块将纠正您看到的黑色填充和粗轴问题

// c3 chart generation code
....


// set the properties that html2canvas does not recognize / assumes wrongly in a way that it does / explicitly
d3.selectAll('#chart *').each(function (e) {
    if (d3.select(this).style('fill-opacity') == 0)
        d3.select(this).style('opacity', 0);
    d3.select(this).style('fill', d3.select(this).style('fill'));
    d3.select(this).style('stroke', d3.select(this).style('stroke'));
});
d3.selectAll('#chart text').each(function (e) {
    d3.select(this).style('font-size', d3.select(this).style('font-size'));
    d3.select(this).style('font-family', d3.select(this).style('font-family'));
});

// html2canvas does not recognize dy
d3.selectAll('#chart tspan').each(function (e) {
    // convert em to px
    if (d3.select(this).attr('dy').indexOf('em') !== -1 && d3.select(this).style('font-size').indexOf('px') !== -1) {
        d3.select(this).attr('dy', d3.select(this).attr('dy').replace('em', '') * d3.select(this).style('font-size').replace('px', ''));
    }

    if (d3.select(this).attr('dy') != 0) {
        d3.select(this.parentNode).attr('y', Number(d3.select(this.parentNode).attr('y')) + Number(d3.select(this).attr('dy')));
        d3.select(this).attr('dy', 0);
    }
});



// html2canvas code
....

如果您正在使用其他库,您可能需要根据它所理解的 CSS 属性向上述块添加/删除。

【讨论】:

猜你喜欢
  • 2011-09-09
  • 2018-03-17
  • 2019-10-17
  • 2015-11-20
  • 2011-04-30
  • 2019-04-10
  • 2016-06-02
  • 2017-09-01
  • 1970-01-01
相关资源
最近更新 更多