javascript - 如何在 d3 版本 4 中添加 SVG 作为图像+xml?

标签 javascript d3.js svg

我有一个 svg,其中包含可以作为 xml 读取的对象。我无法在版本 4 中使用 d3.xml 函数,因此在读取 svg 内的对象时遇到问题。目前我已经添加了这样的 svg:

var sketchSVG = d3.select("#sketch4").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(sketchZoom.on("zoom", sketchZoomCallback))
    .append("g");

sketchSVG.append("svg:image")
    .attr("xlink:href", "img/sketch_all_in_components_web.svg")
    .attr("width", 560)
    .attr("height", 560)
    .attr("x", 0)
    .attr("y", -78);

这里的问题是我只能在html页面上看到svg作为图像,就好像里面没有对象一样。我也想读取这些对象,只有将 svg 添加为 image+xml 才能完成。我怎样才能实现这个目标?

最佳答案

如果您通过 d3.request 检索 SVG 文件,xhr.responseXML属性是一个文档实例。您可以选择根<svg>并直接追加。

将缩放行为附加到外部 svg,如上所示,并将检索到的 svg 附加为其子级:

var sketchZoom = d3.zoom();
var sketchSVG = d3.select("#sketch4").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(sketchZoom.on("zoom", sketchZoomCallback));

function responseCallback (xhr) {
    sketchSVG.append(function () {
            return xhr.responseXML.querySelector('svg');
        }).attr("width", 560)
        .attr("height", 560)
        .attr("x", 0)
        .attr("y", -78);
}

d3.request("img/sketch_all_in_components_web.svg")
    .mimeType("image/svg+xml")
    .response(responseCallback)
    .get();

关于javascript - 如何在 d3 版本 4 中添加 SVG 作为图像+xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48869429/

相关文章:

javascript - Onclick 下载按钮到移动设备的图像

javascript - 使用 jQuery 中的 onchange 函数从多个动态记录中获取选择选项值?

reactjs - 将 dc.js 转换为 React 有意义吗?

editor - 有什么好的小型或基础SVG编辑器?

用于绘制 SVG 元素的 JavaScript 函数

javascript - 为什么我的循环不运行

javascript - 如何防止绝对定位的弹出窗口从其容器中剪出?

javascript - 对使用 d3.js 的 SVG 样式感到困惑

javascript - 如何将自定义(定义的)顺序应用于 DC.js 中的行图表的行?

html - 仅使用 CSS 为 SVG 着色?