Sunday 3 January 2021

D3.js How to append local image

I have this project where I need to add local images. At this point it is possible to add images that are located on a URL using svg images and xlink:href.

But the images I am using are located in a local folder inside my project src/assets/img or @/assets/img(ES6 import using at ('@')).

But I cannot get the images to load in. If I add the src attribute to the image the src is being set to http://localhost:8080/@/assets/img/arrow.svg and not to the actual source of the image in the project.

If I inspect the DOM tree in the Chrome console a normal img would look like this:

enter image description here

While the img that is being appended by D3js is not being inserted correctly and when I hover over the src it shows: http://localhost:8080/@/assets/img/arrow.svg

enter image description here

The d.data[2] contains the name of the actual image e.g. 'arrow.svg' I have also tried to change src to xlink:src:

g.append("img")
      .attr("transform", function(d) {
        var x = arc.centroid(d)[0] - image_width / 2;
        var y = arc.centroid(d)[1] - image_height / 2;
        return "translate(" + x + "," + y + ")";
      })
      .attr("src", function(d) {
        return "@/assets/img/" + d.data[2];
      })
      .attr("width", image_width)
      .attr("height", image_height);

This is a working example when the images are located on a URL:

g.append("svg:image")
      .attr("transform", function(d) {
        var x = arc.centroid(d)[0] - image_width / 2;
        var y = arc.centroid(d)[1] - image_height / 2;
        return "translate(" + x + "," + y + ")";
      })
      .attr("xlink:href", function(d) {
        return d.data[2];
      })
      .attr("width", image_width)
      .attr("height", image_height);


from D3.js How to append local image

No comments:

Post a Comment