简体   繁体   English

在Javascript中将多个SVG元素转换为PNG

[英]Converting more than one SVG element to PNG in Javascript

I have a simple chart that uses 3 d3.js SVG elements to display different stuff. 我有一个简单的图表,该图表使用3 d3.js SVG元素显示不同的内容。 I want to convert that to PNG. 我想将其转换为PNG。 I found this solution on here: 我在这里找到了这个解决方案:

function saveImage(){

var html = d3.selectAll("svg")
    .attr("version", 1.1)
    .attr("xmlns", "http://www.w3.org/2000/svg")
    .node().parentNode.innerHTML;

var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html);
var img = '<img src="'+imgsrc+'"/>';
d3.select("#svgdataurl").html(img);
console.log(html);
};

Now this probably works fine, if i would only use one SVG element, but if i try this, i get this error: 现在,如果我仅使用一个SVG元素,则此方法可能会正常工作,但如果尝试此操作,则会出现此错误:

This page contains the following errors:

error on line 1 at column 419: Extra content at the end of the document 

Column 419 is, of course directly between the first closing < /svg> tag and the next opening < svg> tag. 当然,列419直接在第一个关闭</ svg>标签和下一个打开的<svg>标签之间。

Is it possible to convert all 3 elements into one picture using only javascript? 是否可以仅使用javascript将所有3个元素转换为一张图片?

I'm not familiar with d3.js , 我不熟悉d3.js,

Before that, I have to know that, Does your code working well for single svg? 在此之前,我必须知道,您的代码对于单个svg是否工作良好? You got a error on multiple svg used right? 您在使用多个svg时出错了吗?

If it is, you will try the following code 如果是这样,您将尝试以下代码

function saveImage(){

var html = d3.selectAll("svg")
    .attr("version", 1.1)
    .attr("xmlns", "http://www.w3.org/2000/svg")
    .node().parentNode.innerHTML;
for(var i=0;i<html.length;i++)
{
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html[i]);
var img = '<img src="'+imgsrc+'"/>';
d3.select("#svgdataurl").html(img);
console.log(html[i]);
}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM