surya surya - 1 month ago 6
HTML Question

SVG element from an array

I am trying to load images into a svg canvas from an array and I am not able to make this code work.

I am trying to debug it with Chrome and I am not able to. The image is blank and I don't know how to proceed.

<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<style type="text/css">
body {
background-image:url('BG.png')
}
</style>
<title>Drag And Drop</title>
</head>
<body>
<script type="text/javascript">

window.onload = function(){
var NumImages = [
{ 'x' :200, 'y':90, 'width': 450, 'height':200, 'href' : 'numbers.jpeg' },
];
var circleData = [
{ "cx": 20, "cy": 20, "radius": 20, "color" : "green" },
{ "cx": 70, "cy": 70, "radius": 20, "color" : "purple" }];


var rectangleData = [
{ "rx": 110, "ry": 110, "height": 30, "width": 30, "color" : "blue" },
{ "rx": 160, "ry": 160, "height": 30, "width": 30, "color" : "red" }];

var svgContainer = d3.select("body").append("svg")
.attr("width",700)
.attr("height",700)
.attr("margin-top", 100);


var images = svgContainer.selectAll("image")
.data(NumImages)
.enter()
.append("image");

svgContainer.append("image")
.attr('x',200)
.attr('y',90)
.attr('width', 50)
.attr('height', 200)
.attr("xlink:href", "2-image.jpg");
};

</script>

</body>
</html>

Answer

You've done all the hard work, you just need to adjust the last couple of lines. You need to use the data that you've bound to the images variable so try this;

images
    .attr('x', function (d,i) { return d.x; })
    .attr('y', function (d,i) { return d.y; })
    .attr('width', function (d,i) { return d.width; })
    .attr('height', function (d,i) { return d.height; })    
    .attr("xlink:href", function (d,i) { return d.href; });
Comments