3

Here is my problem. My graph currently looks like this: enter image description here Which is dandy. However, I want the black squares on top to be filled with pictures. Luckily I have a CSS file that has pictures linked with classes. I also have a JSON file that contains all the class names. All those class names are assigned to the squares and I can see the picture in the inspect element on Chrome. The only issue is the pictures don't appear in the square. (Also my axises broke, but that is secondary concern). CSS, JSON

This is where I'm assigning classes and creating the rectangles.

svg.selectAll(".div")
    .data(data.chartData, function(d){return d.vNm;})
    .enter().append("rect")
    .attr("x", function(d){
        return x(d.vNm);
    })
    .attr("y", function(d){
        return (y(d.values.reduce(function(sum, d){
            return sum + d.amount;
        }, 0))) - 64.5;
    })
    .attr("width", 43)
    .attr("height", 43)
    .attr("class", function(d){return d.vId;})
    .style("fill", function(d) { return segColor(d.data.type); });
Alexey Ayzin
  • 209
  • 2
  • 21
  • please show us some examples of your code – Noam Hacker May 19 '16 at 20:12
  • @NoamHacker you need more? – Alexey Ayzin May 19 '16 at 20:18
  • @AlexeyAyzin You are using SVG, so this is not possible. Setting a background image via CSS only works on "regular html" elements. So either you have to take the SVG approach to background images ([like this](http://stackoverflow.com/questions/3796025/fill-svg-path-element-with-a-background-image) for example), or perhaps you can figure out how to use "regular html" to render your chart. – meetamit May 19 '16 at 23:13

2 Answers2

1

One approach to solve your problem is to use html elements like div for the images above the chart instead of svg elements, so you can use the full power of css.

Luckily you don't need to calculate the position of those html elements by yourself, there are some libraries that help you position the images correctly above the bars in the chart.

Check out https://popper.js.org/ for example, you can just call its API for each bar you render using d3.js:

 var popper = new Popper(barElement, onPopper, {
        placement: 'top'
    });
paradite
  • 6,238
  • 3
  • 40
  • 58
1

SVG elements do not follow exactly the same CSS rules as typical HTML elements.

In your case, background-image doesn't work.

The least painful way to achieve the effect would be to embed an <image> tag after the <rect>:

<image width="100" height="100" xlink:href="data:image/png;base64,...">

It means that you have to modify your JSON to store the image's base64 data in there instead of CSS.

Thach Mai
  • 915
  • 1
  • 6
  • 16