Examples of drawing dynamic progress bars Based on D3.js, d3.js instances

Source: Internet
Author: User

Examples of drawing dynamic progress bars Based on D3.js, d3.js instances

What is D3?

D3 is a Data-Driven document. Listening to the name is a bit abstract. To put it simply, it is actually a JavaScript function library which is mainly used for data visualization. If you do not know what JavaScript is, take a look at JavaScript first. We recommend that you use the tutorial.

The extension name of JavaScript files is usually. js, so D3 is often called D3.js. D3 provides a variety of easy-to-use functions, greatly simplifying the difficulty of JavaScript data operations. Because it is essentially JavaScript, JavaScript can also implement all functions, but it can greatly reduce your workload, especially in data visualization, d3 has reduced the complex steps for generating visualization to several simple functions. You only need to input a few simple data items to convert them into various beautiful images. It is easy to understand JavaScript.

During website page loading and form submission, progress bars are often used to express the loading process to optimize the user experience. common progress bars include rectangular and circular progress bars, as shown in:

 

We often use svg or canvas to draw dynamic images, but the painting process is relatively cumbersome. For visual and beautiful progress bars, the Community also provides mature solutions such as highcharts/ECharts. However, the configuration-based development method cannot implement custom rendering of 100%. This article will show you how to use D3.js to implement a dynamic progress bar step by step and share the code logic principles.

Basic Requirements

  • Learn how to draw basic images with svg
  • Learn about D3.js v4
  • Learn how to use D3.js (v4) to draw basic svg Images

Draw a circular progress bar

For a circular progress bar, we first split the task:

  • Draw nested arc
  • Real-time data display at the center
  • Show animations
  • Beautification

1. Draw nested Arcs

For circles, svg provides existing circle labels for use. However, the disadvantage is that circle labels can be used for circular progress bars. However, for further extension of graphs, such as semi-circle drawing, the processing of circle is tricky. D3.js provides arc-related APIs to encapsulate the circular rendering method:

var arc = d3.arc()   .innerRadius(180)   .outerRadius(240)   //.startAngle(0)   //.endAngle(Math.PI)arc(); // "M0,-100A100,100,0,0,1,100,0L0,0Z"

The above code implements the drawing logic for two nested circles. d3.arc () returns an arc constructor and uses a chain call to set the radius, starting angle, and ending angle of the inner and outer circles. Run the arc () constructor to obtain the path data bound to <path>. The complete code is as follows:

<!--html--><svg width="960" height="500"></svg><script> var arcGenerator = d3.arc().innerRadius(80).outerRadius(100).startAngle(0); var picture = d3.select('svg').append('g').attr('transform','translate(480,250)');</script>

The above code implements two steps:

1. Generate the arcGenerator with 0 degrees as the starting point

2. Set the transform Image offset so that the image is located in the center of the canvas.

Currently, there are no elements on the canvas. Next we will draw the actual image.

var backGround = picture.append("path")  .datum({endAngle: 2 * Math.PI})  .style("fill", "#FDF5E6")  .attr("d", arcGenerator);

We add the <path> element to the canvas picture. Based on the endAngle () feature, use the datum () method to convert {endAngle: Math. PI}, that is, the end point angle 2π is bound to the <path> element, and the arc constructor is assigned to path d. In this way, the arc of the specified background color is generated. The actual figure is as follows:

The first arc is drawn, so according to the hierarchical relationship z-index of svg, the so-called progress bar is actually the second arc covering the first layer of the arc. Likewise:

var upperGround = picture.append('path')  .datum({endAngle:Math.PI / 2})  .style('fill','#FFC125')  .attr('d',arcGenerator)

After the code is run, you can:

 

2. Real-time data display at the center

In the first part, we have implemented nested circles based on two paths. The second part shows the real-time data at the center of the circle. When loading the progress bar, we add data at the center of the circle to express the current loading progress. Use the <text> label for display:

var dataText = g.append('text')  .text(12)  .attr('text-anchor','middle')  .attr('dominant-baseline','middle')  .attr('font-size','38px')

Temporarily set the data to 12 and set the horizontal and vertical center. The effect is as follows:

 

3. Show animations

We have learned from the following two parts:

  • The essence of drawing a progress bar is to change the angle of the upper arc.
  • An integral circle when the radian is 2 π and a half circle when the radian is π
  • The data in the circle is the percentage of the current radians relative to 2 π.

In summary, we only need to change the radians and values while setting the length of the change process to achieve the so-called "Animation ". In the official instance provided by ECharts, setInterval is used to update data at a fixed interval. In fact, similar methods are also provided in D3.js to implement the setInterval-like function:

d3.interval(function(){ foreground.transition().duration(750).attrTween('d',function(d){  var compute = d3.interpolate(d.endAngle,Math.random() * Math.PI * 2);  return function(t){   d.endAngle = compute(t);   return arcGenerator(d);  }   })},1000)

Disassemble this Code:

  • The d3.interval () method provides the setInterval () function.
  • Selection. transition. duration () sets the time required for the transition of the current DOM attribute to the process of the specified DOM attribute, in milliseconds
  • Transation. attrTween is the interpolation API. What is interpolation?

In summary, inserting a function in a given discrete data enables this continuous function to pass through all data points. For example, given a div, how can we calculate the color value of each region to realize the linear gradient of the background color from the red on the left to the green on the right? Only:

var compute = d3.interpolate(d3.rgb(255,0,0),d3.rgb(0,255,0));

Compute is an interpolation function. The parameter range is [0, 1]. If you enter a number in the range, the compute function returns the corresponding color value. What is the use of such interpolation? You can see:

 

Assume that the div length width is 100, convert [0,100] to the range data of [] in a proportional relationship, and enter the compute function to obtain the color of a region. Of course, we should not use discrete data as input and output for linear area processing. Therefore, D3.js provides more convenient linear gradient API d3.linear, which will not be described here.

Coded3.interpolate(d.endAngle,Math.random() * Math.PI * 2); Implemented the following interpolation range:

["Current angle value", "random angle value"] // express range rather than Array

Then, a function with the parameter t is returned. What is the role of the function?

The t parameter is similar to the d parameter. It is an internal interpolation implemented by D3.js. Its range is [0, 1]. The t parameter automatically calculates the appropriate number of interpolation values in [0, 1] based on the set duration () duration and returns the interpolation result to achieve a linear and stable transition animation effect.

To complete the animation loading effect of the scroll bar, we will write the logic for changing the real-time data in the center of the circle, as long as simple assignment is implemented. The complete code is as follows:

D3.interval (function () {foreground. transition (). duration (1, 750 ). attrTween ('D', function (d) {var compute = d3.interpolate (d. endAngle, Math. random () * Math. PI * 2); return function (t) {d. endAngle = compute (t); var data = d. endAngle/Math. PI/2*100; // set the value d3.select ('text '). text (data. toFixed (0) + '%'); // pass in the new parameter to generate the new arc constructor return arcGenerator (d) ;}}, 2000)

The final result is as follows:

 

4. beautification

We have implemented the most basic progress bar style and functions in part 1, 2, and 3, but the style looks monotonous. Next we will perform linear gradient processing on the progress bar. We use the linear interpolation API provided by D3.js:

var colorLinear = d3.scaleLinear().domain([0,100]).range(["#EEE685","#EE3B3B"]);

ColorLinear is also an interpolation function. If we input a value in the range [0,100], the color value corresponding to the range ["# EEE685", "# EE3B3B"] is returned. For example, when the progress bar shows "80%:

Var color = colorLinear (80); // color indicates the color value corresponding to "80% ".

After the color value is realized, we only need to change the original color when the progress bar changes:

D3.interval (function () {foreground. transition (). duration (1, 750 ). attrTween ('D', function (d) {var compute = d3.interpolate (d. endAngle, Math. random () * Math. PI * 2); return function (t) {d. endAngle = compute (t); var data = d. endAngle/Math. PI/2*100; // set the value d3.select ('text '). text (data. toFixed (0) + '%'); // pass in the new parameter to generate the new arc constructor return arcGenerator (d );}}). styleTween ('fill', function (d) {return function (t) {var data = d. endAngle/Math. PI/2*100; // return the color value of the value returned colorLinear (data) ;}}, 2000)

Similar to attrTween, styleTween is an interpolation function for style change. You can set both the progress bar value and color in the form of a chained call. The final result is as follows:

 

In summary, we have achieved a circular progress bar with color changes under different values, which can be used in alarm, reminder, and other business scenarios.

Draw rectangular progress bar

The rectangular progress bar is much simpler than the circular progress bar. Based on the interpolation principle, You can smoothly change the length of the rectangle. Directly run the Code:

The implementation result is as follows:

 

Summary

The key point of drawing a progress bar based on D3.js is interpolation, so as to smoothly transition the graph correctly. It is also feasible to use svg or pure css to implement the progress bar of Rectangles and circles, but the processing of paths and animations and css writing requirements are complicated. We have observed that the logic code for drawing the above two Progress Bars Using D3.js is almost completely implemented using js. At the same time, the amount of code can be controlled in about 20 lines and can be encapsulated and reused, which is very refined, it is advantageous in developing custom charts.

For the derived dashboard chart of the progress bar, the scale description and pointer calculation are added compared to the basic progress bar. However, if you master the interpolation principle and usage, you can easily process similar charts.

The above is an example of how to draw a dynamic progress bar based on D3.js. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.