如何在SVG中导出PNG

4

我在导出包含PNG图片的SVG文件时遇到了一些问题。我使用的是D3JS,以下是代码:

mysvg.append("image")
  .attr("width", 299)
  .attr("height", 168)
  .attr("xlink:href", "image.png")

var html = d3.select("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("#chartRender").html(img);

似乎出现了错误:图像上的命名空间前缀xlink在href上未定义。PNG图像在SVG容器中正确显示,但未在#chartRender中显示。
有任何想法吗?
更新1: 在画布中绘制图像可以解决问题。
canvas = d3.select("body").append("canvas").attr("id", "newCanvas")
  .attr("width", "200px").attr("height", "100px").node()
context = canvas.getContext('2d')
imageObj = new Image()
imageObj.src = params.url
imageObj.onload = -> context.drawImage(imageObj, 0, 0)

但是显示的数据为空内容:(

imageData = canvas.toDataURL("image/png")
d3.select("body").append("img").datum(imageData).attr("src", (d)-> return d)
d3.select("svg").append("image").datum(imageData).attr("height", "100")
  .attr("width", "200").attr("xlink:href", (d)-> return d)

1
如果您从<img>元素引用svg,则由于安全原因,浏览器会阻止所有外部引用。您需要将png转换为数据URI才能在特定情况下使其正常工作,或者使用<iframe>或<object>引用svg。例如,请参见http://stackoverflow.com/a/20816406/109374。 - Erik Dahlström
1个回答

1

你需要在svg标签中添加xmlns:xlink

它应该像这样:

<svg width="xxx" height="yyy" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

所以只需这样做...

.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")

更新

我创建了一个JSBIN来帮助我们解决这个问题。它运行得非常顺利。

var mysvg = d3.select('#mysvg');

var src = 'http://placehold.it/350x150';

mysvg.append("image")
  .attr("width", 350)
  .attr("height", 150)
  .attr("xlink:href", src);

var img = document.createElement('img');
    img.src = src;

document.getElementById("target").appendChild(img);

它解决了你的问题吗?


谢谢你的回答。看起来它似乎不起作用。导出的图现在是空的 :( 如果我从SVG中删除图像(在代码中),那么它可以工作,但没有图像(显然):( - Yves Lange
你的图片是否有相对路径? - rafaelcastrocouto
是的,它在根目录下,名为:image.png。 - Yves Lange
尝试设置绝对路径...也许这就是你的问题...不管怎样,这是另一个问题,对吧?如果是这样,那么你应该发布另一个问题。 - rafaelcastrocouto
我认为这不是问题所在。我已经按照你的建议添加了内容,但仍然出现相同的问题:“Uncaught NamespaceError: Failed to execute 'setAttributeNS' on 'Element': 'http://www.w3.org/2000/xmlns/' is an invalid namespace for attributes.” - Yves Lange
我已经更新了我的问题。这绝对不是路径的问题,因为它可以在Canvas容器中绘制。 - Yves Lange

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