Rose Kane Quinn Rose Kane Quinn - 6 months ago 28
Javascript Question

Added image to DOM element in d3 but now it won't transition

I'm trying to get an element with an appended image to transition using the d3.js library; I had successfully achieved this just using a plain circle that transitioned nicely around the screen but now that I've added a png the transition doesn't happen - the png does appear though when the page is refreshed, it just won't move like it did before! My code is below.. your help is appreciated!

<script>

var data = [60, 120, 40, 710, 560, 850];
var data1 = data[0];

var canvas = d3.select("body").append("svg")
.attr("width", 2000)
.attr("height", 2000);

var imgs = canvas.append("image")
.attr("xlink:href", "AWT-Bus.png")
.attr("x", "60")
.attr("y", "60")
.attr("width", "20")
.attr("height", "20")
.attr("cx", 50)
.attr("cy", 200)
.attr("r", 20)
;

imgs.transition()
.duration(data1*100)
.delay(2000)
.attr("cx", 200)
.transition()
.attr("cx", 50)
.attr("cy", 200)
.transition()
.attr("cx", 150)
.attr("cy", 300)
;



Joe Joe
Answer

The attributes you are changing in your code (cx and cy) are applicable to circles which are described by the x and y co-ordinates of their center (cx and cy) plus the radius (r). This is why your circle example worked.

But images are described by their width, height and the x and y co-ordinates of the upper-left corner of the box (using x and y attributes as shown below).

Different svg elements have different attributes which describe their dimensions and their location on the page, so you need to be aware of the different attributes that each type of element has, perhaps using a reference such as https://developer.mozilla.org/en-US/docs/Web/SVG/Element. Then you can animate your svg element using transition as you have done in your code and changing the value of the appropriate attribute.

var canvas = d3.select("body").append("svg")
  .attr("width", 2000)
  .attr("height", 2000);

var imgs = canvas.append("image")
  .attr("xlink:href", "AWT-Bus.png")
  .attr("x", "60")
  .attr("y", "60")
  .attr("width", "20")
  .attr("height", "20");

imgs.transition()
  .duration(2000)
  .delay(1000)
  .attr("x", 200)
  .transition()
  .attr("x", 50)
  .attr("y", 200)
  .transition()
  .attr("x", 150)
  .attr("y", 300);