如何在SVG中导出PNG

How to export PNG within SVG

本文关键字:PNG SVG      更新时间:2023-09-26

我有一些麻烦导出我的SVG,其中包含一个PNG图像。我使用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中显示

你知道吗?

在画布上绘制图像

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)

你需要添加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);

它能解决你的问题吗?