Reputation: 55
I could locate rectangle using the following. I want to replace these rectangles with image/icon(jpg/url)
for(var i=0; i< tempdata.length; i++)
{
var name = "rect"+i;
d3.select("#floor svg").selectAll('rect')
.data(tempdata).enter()
.append("svg:rect")
.attr("stroke", "black")
.attr("fill", (d,i)=>tempdata[i].SENSOR_COLOR)
//.attr("r", 5)
.attr("width", 20)
.attr("height", 20)
.attr("x", (d,i)=>tempdata[i].CX)
.attr("y", (d,i)=>tempdata[i].CY)
.attr("idCircle",(d,i)=>name)
}
Upvotes: 2
Views: 941
Reputation: 102174
First of all: don't use for
loops to retrieve data in D3. D3 already provides all you need to bind and retrieve your data. Indeed, there are several situations where it's a good idea to use a for
loop, but this is not one of them.
Regarding your question: instead of append("rect")
, you have to use append("image")
:
var images = svg.selectAll(".images")
.data(data)
.enter()
.append("image");
In this demo snippet, I set the url of the images in the data
array, using a key conveniently named url
. Then, you have to append them using:
.attr("xlink:href", function(d){return d.url})
Here is the demo snippet, using favicons:
var svg = d3.select("body")
.append("svg")
.attr("width", 200)
.attr("height", 200);
var data = [{url:"https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2009/02/amazon.gif", x:20, y:40},
{url:"https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2009/02/skype.gif", x:90, y:110},
{url: "https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2009/02/espn.gif", x:150, y:150},
{url: "https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2009/02/twitter.gif", x:180, y:50}];
var images = svg.selectAll(".images")
.data(data)
.enter()
.append("image");
images.attr("xlink:href", function(d){return d.url})
.attr("x", function(d){return d.x})
.attr("y", function(d){return d.y})
.attr("width", 16)
.attr("height", 16);
<script src="https://d3js.org/d3.v4.min.js"></script>
Upvotes: 3