Salman
Salman

Reputation: 431

How to add SVG as an image+xml in d3 version 4?

I have an svg having objects inside it which can be read off as xml. I am not able to use d3.xml function in version 4 so I am having problem in reading the objects inside the svg. At the moment I have added the svg like this:

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);

The problem here is that I can only see the svg as an image on the html page as if there are no objects inside. I want to read those objects as well which can only be done if I add the svg as image+xml. How can I achieve this?

Upvotes: 1

Views: 994

Answers (1)

ccprog
ccprog

Reputation: 21811

If you retrieve a SVG file via d3.request, the xhr.responseXML property is a document instance. You can select the root <svg> and append it directly.

Attach the zoom behavior to an outer svg as above and append the retrieved svg as its child:

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();

Upvotes: 1

Related Questions