zobel
zobel

Reputation: 281

How to insert images into d3 hexbin

I created a mesh of hexagons using D3's hexbin. I want to fill the hexagons with images. I took a look at this question where a circle is filled with an image. I tried to do exactly the same and fill every bin with the image but it didn't work.

This is what i tried:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.hexagon {
  fill: none;
  stroke: #000;
  stroke-width: 2px;
}

</style>

<body>
  <svg id="mySvg" width="80" height="80">
    <defs id="mdef">
      <pattern id="image" x="0" y="0" height="40" width="40">
        <image x="0" y="0" width="40" height="40" xlink:href="http://www.e-pint.com/epint.jpg"></image>
      </pattern>
    </defs>
  </svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/d3.hexbin.v0.min.js?5c6e4f0"></script>
<script>

var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 900 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var color = d3.scale.linear()
    .domain([0, 20])
    .range(["orange", "orange"])
    .interpolate(d3.interpolateLab);

var hexbin = d3.hexbin()
    .size([width, height])
    .radius(100);

var points = hexbin.centers();

var x = d3.scale.identity()
    .domain([0, width]);

var y = d3.scale.linear()
    .domain([0, height])
    .range([height, 0]);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)

svg.append("clipPath")
    .attr("id", "clip")
  .append("rect")
    .attr("class", "mesh")
    .attr("width", width)
    .attr("height", height);

svg.append("g")
    .attr("clip-path", "url(#clip)")
  .selectAll(".hexagon")
    .data(hexbin(points))
  .enter().append("path")
    .attr("class", "hexagon")
    .attr("d", hexbin.hexagon())
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
    .style("fill", 'url(#image)');

</script>

So how can i fill the hexagons with an image?

Upvotes: 2

Views: 1345

Answers (1)

Mike Precup
Mike Precup

Reputation: 4218

Looks like your pattern just wasn't defined in a way that would show up in the path. This should move the image to the right part of the pattern to show up in your hex grid.

<pattern id="image" x="-100" y="-100" height="200" width="200">
    <image x="50" y="50" width="100" height="100" xlink:href="http://www.e-pint.com/epint.jpg"></image>
</pattern>

Upvotes: 1

Related Questions