svg - 将SVG转换为PNG并保持CSS完整性

标签 svg d3.js png librsvg

我目前正在使用canvg()和Canvas2Image将我的SVG复制到 Canvas ,然后将 Canvas 转换为PNG。我想保持图像格式而不使用PDF。

如何维护CSS完整性?图表是使用NVD3.js制作的。

downloadPhoto: function() {
  var chartArea = document.getElementsByTagName('svg')[0].parentNode;
  var svg = chartArea.innerHTML;
  var canvas = document.createElement('canvas');
  canvas.setAttribute('width', chartArea.offsetWidth);
  canvas.setAttribute('height', chartArea.offsetHeight);
  canvas.setAttribute('display', 'none');

  canvas.setAttribute(
    'style',
    'position: absolute; ' +
    'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
    'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
  document.body.appendChild(canvas);
  canvg(canvas, svg);
  Canvas2Image.saveAsPNG(canvas);
  canvas.parentNode.removeChild(canvas);
}

最佳答案

在样式表中定义的svg元素的样式定义不会应用于生成的 Canvas 。可以通过在调用canvg之前向svg元素添加样式定义来修补此问题。

this article启发,我创建了以下代码:

function generateStyleDefs(svgDomElement) {
  var styleDefs = "";
  var sheets = document.styleSheets;
  for (var i = 0; i < sheets.length; i++) {
    var rules = sheets[i].cssRules;
    for (var j = 0; j < rules.length; j++) {
      var rule = rules[j];
      if (rule.style) {
        var selectorText = rule.selectorText;
        var elems = svgDomElement.querySelectorAll(selectorText);

        if (elems.length) {
          styleDefs += selectorText + " { " + rule.style.cssText + " }\n";
        }
      }
    }
  }

  var s = document.createElement('style');
  s.setAttribute('type', 'text/css');
  s.innerHTML = "<![CDATA[\n" + styleDefs + "\n]]>";
  //somehow cdata section doesn't always work; you could use this instead:
  //s.innerHTML = styleDefs;

  var defs = document.createElement('defs');
  defs.appendChild(s);
  svgDomElement.insertBefore(defs, svgDomElement.firstChild);
}

// generate style definitions on the svg element(s)
generateStyleDefs(document.getElementById('svgElementId'));

关于svg - 将SVG转换为PNG并保持CSS完整性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20394041/

相关文章:

javascript - 不显示线路连接器但显示端点

javascript - 如何将foreignObject附加到svg图像

css - 背景重复似乎在 IE6 中不起作用

image - 是否可以将 png 转换为分层 PSD 文件?

javascript - nvd3.js-带取景器的折线图 : rotate axis labels and show line values when mouse over

javascript - CSS/SVG/动画 : Apply transform origin to a single element within svg not working

javascript - Axis 和 svg 文本元素相互隐藏

javascript - 将 D3.js 与模块模式结合使用

javascript - 将平行坐标库(d3.js)导入到jsfiddle

c++ - 如何让png具有透明属性