将内联SVG转换为PNG时出现样式错误

3
我的高级目标是将包含几个内联svg图像的
元素转换为png文件。所有操作必须在客户端浏览器中使用JavaScript执行。我已经尝试过:
  1. 使用canvg库并按照此帖子的步骤:https://github.com/niklasvh/html2canvas/issues/95#issuecomment-34439223

    原始svg:

    original svg

    结果:

    canvg result

  2. 将css样式压缩到<svg>标签中,然后调用canvg,按照此帖子的步骤:Convert embedded SVG to PNG in-place

    结果:一张空白图片。

  3. 将css样式压缩到<svg>标签中,然后手动将svg绘制到画布上,按照此帖子的步骤:how to save/ export inline SVG styled with css from browser to image file

    结果:一张空白图片。

  4. 使用以下代码将css样式压缩到内联样式表中:http://spin.atomicobject.com/2014/01/21/convert-svg-to-png/

    结果:一张空白图片。

  5. 使用svg crowbar手动将<div>元素下载为.svg文件。

    结果:

    enter image description here

    然后,当我比较原始svg的计算css与下载的svg时,我发现下载的svg具有正确的svg xml,但是错误的内联样式表(<style type="text/css">)例如图表右侧的200、300数字,它们是用<text x="214" dy=".32em" y="0" style="text-anchor: start;">200</text>绘制的,在我的外部css中,我有:

    .scatterChart .axisGraphicsContext text { font-size: 8px; fill: #777; }

    然而,下载的svg的字体大小和填充属性在内联样式表中缺失。

1个回答

2

我一直在寻找一种解决方案,可以通过Rickshaw(基于D3)创建的CSS导出PNG。我找到的唯一解决方案是:

  • treat the DIVs different from the SVGs, and treat them all individually
  • convert the DIVs (and other non-SVG content) with html2canvas to canvas
  • make the CSS inline to the SVG; @thirdcreed has posted the JavaScript code and D3 selectors for that at: Rickshaw CSS/Axes in JSDOM - adapt that to your custom CSS as needed.
  • convert the SVGs into canvas with code such as

    var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html2);
    var img = '<img src="'+imgsrc+'">';      
    var canvas = document.querySelector("canvas"),
    context = canvas.getContext("2d");      
    var image = new Image;
    image.src = imgsrc;
    image.onload = function() {
      context.drawImage(image, 0, 0);
    }
    
  • merge the different canvases you have into one
  • convert into image with code such as:

    var canvasdata = canvas.toDataURL("image/png");
    var pngimg = '<img src="'+canvasdata+'">'; 
    d3.select("#pngdataurl").html(pngimg); // contains selector from D3, adjust if you don't use D3
    var a = document.getElementById("some_anchor"); // Fix for Firefox: supply an anchor-tag here that is 'display:none' in your document, otherwise download won't work
    a.download = "sample.png";
    a.href = canvasdata;
    a.click();
    
请注意,除了Internet Explorer浏览器外,每个浏览器都需要SVG具有xmlns属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接