Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.ease fade image in

I am calling the following function and passing it the location of an image:

function show_image(source) {
        var img = d3.select("#right-section").append("img").attr("src",source)
        img.transition().duration(5000).easeLinear;
    }

Here is the function that uses some JQuery to empty the relevant HTML div object (right-section) and then show the image:

function Con1aaRight(div) {
    $("#right-section").empty();  
    show_image("images/netflix.jpg");    
}

The problem is the image is showing but not fading in like I would like it to (with d3.ease in the show_image function). I probably should be using JQuery but I would like to incorporate d3. Similar transition/animation ideas welcome. I am building a scrolling webpage tutorial on a data science topic with text on the left and images on the right.

like image 296
Frederic Bastiat Avatar asked Feb 05 '23 17:02

Frederic Bastiat


1 Answers

The problem here is understanding what is a D3 transition and how it works.

A D3 transition, as the name implies, transitions from one state, or value, to another state.

That being said, you can, for example, transition...

  • A position: from x = 10 to x = 60.
  • A color: from green to blue.
  • A font size: from 10px to 18px.
  • An opacity: from 0.2 to 0.9.
  • A stroke width: from 1px to 5px.

... and several other attributes/styles.

However, you cannot transition this:

  • non-existence ➔ existence

As Bostock, creator of D3, once said (emphasis mine):

When modifying the DOM, use selections for any changes that cannot be interpolated; only use transitions for animation. For example, it is impossible to interpolate the creation of an element: it either exists or it doesn’t. (source)

Solution: transition the opacity of the image:

var body = d3.select("body");

show_image("http://www.defenders.org/sites/default/files/styles/large/public/tiger-dirk-freder-isp.jpg")

function show_image(source) {
  var img = body.append("img").attr("src", source).style("opacity", 0)
  img.transition().duration(5000).ease(d3.easeLinear).style("opacity", 1)
}
<script src="https://d3js.org/d3.v4.min.js"></script>

PS: get rid of that jQuery code. You don't need jQuery when using D3. Mixing jQuery and D3 is not only unnecessary but also, in some cases, it will make things silently break.

like image 144
Gerardo Furtado Avatar answered Feb 07 '23 07:02

Gerardo Furtado