d3.js learning notes-06 (animation)

d3.js study notes-06

1 transition

Transition is a dynamic effect, which changes from the initial state to the target state

1.1 start transition

  • d3.transition([selection],[name]): create a transition object with the parameter selection set; Generally use D3 select("rect"). Transition () format, which can be called multiple times to produce a variety of transitions
  • transition.delay([delay]): set the delay time. The transition will take place after a certain time. The unit is milliseconds.
  • transition. The duration of the transition is set to [duration], in milliseconds. For example, duration(2000), i.e. 2s
  • transition.ease(value[,arguments]): set transition styles, such as linear transition, spring handling, etc.
    example
var rect = svg.append ("rect")
			.attr("fi11","steelblue")
			.attr("x",10)
			.attr("y",10)
			.attr("width",100)
			.attr("height",30);
			.transition()
			.delay(500) //Restart after a delay of 500ms
			.duration (1000) //The transition time is 1000ms
			.ease("bounce") // Transition style
			.attr("width",300);//Set new width

1.2 properties of transition

The attribute here refers to the attribute of the selected element and the feature to be changed
  • transition.attr(name, value): transition the attribute name to the target value, valuc. Value can be a function.
  • transition. Attrtween (name, tweet): use the interpolation function tweet () to transition the attribute name.

    The transition process lasts for 2s, and the attribute width transitions from 100 to 400
  • transition.style(name,value[,priority]): transition the name attribute of CSS style to the target value value. Priority is an optional parameter, which indicates the priority of CSS style. There are only two values: null and important.
  • transition. Styletween (name, tweet [, priority]): use the function tweet to transition the CSS style attribute name. Similar to attrTween().
.style("fi11","steelblue")
.transition()
.style("fi11","red")  // The fill color changes from steelblue to red
  • transition.text(value): at the beginning of the transition, set the text to the value value.
  • transition. Tweet (name, factory): transition the attribute name according to the function factory. attrTween() and styleTween() are both implemented with this function. You need to use tweet() to transition text.
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <scrip src="https://d3js.org/d3.v3.min.js"></scrip>
    <script src="../d3.v3.min.js"></script>   <!--Select any reference method: local/on-line-->
</head>
<style>
</style>
<body>
    <script>
        var svg=d3.select("body")
                    .append("svg")
                    .attr("width", 600)
                    .attr("height", 600)
       var text= svg.append ("text")
			.attr("fill","red")  // Color of text
			.attr("x",100)  // x coordinate of text
			.attr("y",10)   // y coordinate of text
			.attr("dy","1.2em")  // Length of text
			.attr("text-anchor", "end")  // Position of text
            .text(100);  // Text content
            
        var initx= text.attr("x");  // Gets the value of the property x of text
        var initText = text.text();  // Gets the text of text

        var textTran= text.transition()
                        .duration(2000)
                        .tween("text" ,function(){
                            return function(t){
                                d3.select(this)
                                    .attr("x", Number(initx)+t*300)  // The meaning of t is the same as above, and the x coordinate and text content are updated
                                    .text(Math.floor(Number(initText)+t*300));
                            }
                        });
    </script>
</body>
</html>

  • transition.remove(): after the transition, delete the selected element, which is applicable to fade out
rect.transition()
	.attr("width",0)
	.remove()   // When the width of the element becomes 0, the element is deleted

1.3 sub elements

transition()You cannot affect child elements in the selection set

How to select child elements:

  • transition.select(selector): select the first child element matching the selector for transition.
  • transition. Select all (selector): select all child elements that match the selector for transition.
  • transition.filter(selector): filter, and selection Filter() is similar.
var dataset = [100,100,100]:
var g = svg.append("g");
var rect = g.selectAll("rect")   // Add three child elements to the g element: rectangle
			.data(dataset)
			.enter()
			.append("rect")
			.attr("fi11","steelblue")
			.attr("id", function (d,i){ return "rect" + i;})
			.attr("x",10)
			.attr("y",function (d,i){ return 10 +i* 35;})
			.attr("width", function(d.i){return d; })
			.attr( "height",30);
g.transition().select("#Rect1 ") / / select the element whose id is rect1 for transition
			.attr("width",300)

g.transition().selectAll("rect")  // Select all rectangles in the g element
			.attr("width",300)

1.4 each() and call()

**each() in the selection set: * * processes the elements in the selection set separately

p.data(persons)
	.each(function (d,i){
		d.age = 20;
	})

each() in the transition object: transition Each ([type,] listener) supports the response to events
Type indicates the type of event, including: start (execute at the beginning of transition), end (execute at the end of transition) and interrupt (execute when a new transition is called elsewhere during transition execution). When the event occurs, the listener (a function) is called.

g.transition()
	.duration (2000)  // Transition time 2 seconds
	.selectA11("rect")  // Manipulate all rectangles
	.each("start", function(d,i){ 
	console.log("start");   // Output start at the beginning of transition
	})
	.each("end", function (d,i){
	console.log("end");   // Output end at the end of transition
	}
	.attr("width".300);
g.transition()
	.duration (2000)
	.selectAll ("rect")
	.each("interrupt", funetion(d,i){
		console.log("interrupt"):
	})
	.attr("width",300);
setTimeout(function ({  // 
	g.transition()   // Execute a new schedule
	.selectAl1("rect")
	.attr("width",10);
	},1000);

call() in the selection set: pass the selection set itself as a parameter to a function

d3.selectAll("div").call(function) // Pass the selection set as an argument to the function function for use

call() in transition object: transition Call (function [, arguments]) calls function with the transition object itself as a parameter
It is required when using the coordinate axis

var xscale = d3.scale.linear()
			.domain([0,10])
			.range([0,300]):
var xAxis = d3.svg.axis()
			.scale(xScale)
			.orient("bottom")
var g= svg.append("g")
			.attr("class", "axis")
			.attr("transform", "tranalate(50,200)")
			.cal1(xAxis)
// The definition domain of the coordinate axis has changed
xscale.domain([0,50]):
// Define a transition event of 2000ms to make the change of coordinate axis occur slowly
g.transition()
	.duration (2000)
	.cal1(xAxis);

1.5 effect of transition

  • linear:
    It changes linearly and increases at a steady rate with time.
  • cubic: the default method, which gradually speeds up the speed.
  • elastic: approach the end like a spring.
  • back: first retract a little, and then rush to the end.
  • Bounce: how many times do you bounce at the end
    The above methods can be combined with a minus sign (-) and j in/out. There are four methods, such as linear in and linear in out
  • In: move in the positive direction.
  • out: move in the opposite direction.
  • In out: the first half moves in the in mode and the second half moves out.
  • Out in: the first half moves in the out mode and the second half moves in the in mode.

2 timer

setInterval(code,millisec): execute the code periodically until * * clearInterval() * * is called or the window is closed.
setTimeout(code,millisec): execute the code after a specified time.

// Pseudo code
var id = setInterval(draw, 10) ;  // Execute the function draw once after 10ms
clearInterval(id) // Clear the timer by the Id of the timer

d3.timer(function[, delay[,time]): after delaying the relative absolute time, the default value of time is date Now(), and then call function().

d3.timer(draw,1000);  // Call draw after current time delay of 1000ms
d3.timer(draw, 500,+new Date(2015,1,1,15,21,30));  // Compared with 15:21:30 on February 1, 2015 (the month starts from 0), draw is called after a delay of 500ms

3 transitional application scenarios

  • Element just appeared
  • Element just updated
  • Element deleted

4 animation cases

4.1 clock

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title></title>
    <script src="../d3.v3.min.js"></script>
  </head>
  <style>
    /* Clock style */
    .time {
      font-family: cursive;
      font-size: 40px;
      color:red;
    }
  </style>
  <body>
    <script>
      // Returns the time in the specified format
      function getTimeString() {
        var time = new Date(); // Get local current time

        var hours = time.getHours(); // When getting
        var minutes = time.getMinutes(); // Get points
        var seconds = time.getSeconds(); // Get seconds

        hours = hours < 10 ? "0" + hours : hours; // Adjust the format to keep two digits
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        // Return time string
        return hours + ":" + minutes + ":" + seconds;
      }

      var svg = d3.select("body").attr("width", 400).attr("height", 400);
      var text = svg
        .append("text")
        .attr("x", 200)
        .attr("y", 200)
        .attr("class", "time")
        .text(getTimeString());

      function updateTime() {
          text.text(getTimeString());
      }

      // Timer update time, updated once per second
      setInterval(updateTime, 1000)
    </script>
  </body>
</html>

References

[1] LV Zhihua Proficient in D3 JS: interactive data visualization advanced programming [M] Beijing: Electronic Industry Press, 2015:151-172

Tags: Visualization

Posted by Crashthatch on Tue, 17 May 2022 12:23:06 +0300