thmsdnnr
thmsdnnr

Reputation: 1302

SVG Sprite Pattern Not Working in D3

I'm making a force-directed graph in D3 with nodes of countries and links that represent those countries' shared borders. I am trying to make each node (an svg rect) have the background image of the corresponding country's flag. I grabbed the image and offset pixel data from flag-sprites.com.

I am making a list of SVG patterns corresponding to the ID tag on each country and then trying to append that pattern to each rect element with the rect "fill:" attribute.

Here is my code: http://codepen.io/thmsdnnr/pen/ObdQvM

I'm a bit confused because when I use the inspector in Google Chrome, each of my pattern elements has the right ID, each rect has the full background image attached, as well as the appropriate "background-position" offset.

However, each node has the same background image flag. When I try to mock up the URL in the pattern into just normal HTML, it doesn't work either. Can someone see what's going wrong here? I feel like (hope at least) I'm somewhat close...but I'm stuck.

Here's a representative rect and svg pattern from the inspector:

<rect width="25" height="15" style="stroke: none; fill:
url(&quot;#pattern_sy&quot;); 
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" 
x="441.4816383268158" y="382.4837223692339"></rect>

<pattern width="25" height="15" id="pattern_sd"><image
href="//raw.githubusercontent.com/thmsdnnr/learnyounode
/master/flags.png" display="inline-block" background-repeat="no-repeat"
style="background-position: -275px -165px;"></image></pattern>

Upvotes: 1

Views: 264

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102219

Instead of setting background-position in your patterns, set the x and y positions:

.attr("x", function(d) {
    if (cCodeToPos(d.code))
        return cCodeToPos(d.code).split(" ")[0];
}).attr("y", function(d) {
    if (cCodeToPos(d.code))
        return cCodeToPos(d.code).split(" ")[1];
});

Here is your updated Pen: http://codepen.io/anon/pen/bBzydG?editors=0010

Upvotes: 1

Related Questions