简体   繁体   中英

Transition/animate the creation/removal of a DOM element

I'm building a dashboard using d3js that shows a graph on the primary SVG. However, when there is no data, I would like the SVG to not exist since it just looks like a ton of empty white space.

Rather than just appending and removing the SVG as needed, I would like to do this with some type of smooth animation/transition so that the sudden creation of the large DOM element doesn't jar the user or seem like a giant flicker.

My understanding of d3 transitions is that they can be used to remove DOM elements, but not to create them. Is this correct? An idea I had was that maybe I could use d3 transitions to update the size of the SVG, but I'm not sure if that's the best way to go. The attributes not being CSS also removes the possibility of using jQuery animate() I think. If d3 can't do it, what other technologies exist to allow me to achieve the desired affect? jQuery fadeIn() is not what I'm looking for since it would still instantly create the SVG in the entire space.

You can't animate creation directly, but you can animate the size change from zero to desired size as shown in this simple example.

Any graph elements you've created prior to resizing the svg will appear to be "revealed" during the resize.

 var svg = d3.select('body').append('svg') .attr('height', 0) .attr('width', 0) svg.append('rect') .attr('fill', 'lightgrey') .attr('width', '100%') .attr('height', '100%') // a stand-in for your normal graph-building logic: svg.append('circle') .attr('cx', 150) .attr('cy', 150) .attr('r', 10) .attr('fill', 'blue') svg.transition().duration(1200) .attr('height', 300) .attr('width', 300) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM