【问题标题】:How to export PNG within SVG如何在 SVG 中导出 PNG
【发布时间】:2014-05-22 10:53:34
【问题描述】:

我在导出包含 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);

似乎发生了错误:Namespace prefix xlink for href on image is not defined。 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)

【问题讨论】:

  • 如果您从 元素引用 svg,出于安全原因,所有外部引用都会被浏览器阻止。您需要将 png 转换为数据 uri 以使其在该特定场景中工作,或使用

标签: javascript html svg d3.js


【解决方案1】:

您需要将xmlns:xlink 添加到您的 svg 标签中。

应该是这样的:

<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 中删除图像(在代码中),那么它可以工作但没有图像(显然):(
  • 你的图片有相对路径吗?
  • 是的。它在根目录中,名为:image.png
  • 尝试设置绝对路径...也许这是您的问题...无论如何,这是另一个问题,对吧?如果是,那么您应该发布另一个问题。
  • 我认为这不是问题所在。我已经添加了你的建议,但仍然是同样的问题Uncaught NamespaceError: Failed to execute 'setAttributeNS' on 'Element': 'http://www.w3.org/2000/xmlns/' is an invalid namespace for attributes.
猜你喜欢
  • 2017-02-28
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 2016-03-11
  • 2017-10-05
  • 2013-07-01
  • 2020-09-01
相关资源
最近更新 更多