search
HomeWeb Front-endJS TutorialD3.js implements dynamic dial effect

This time I will bring you D3.js to realize the dynamic dial effect. What are the precautions for D3.js to realize the dynamic dial effect. The following is a practical case, let's take a look.

This article introduces an example of D3.js implementing a simple and practical dynamic dashboard, and shares it with everyone. The details are as follows:

Dynamic renderings:

Dashboard Rendering

If you look closely at the dynamic rendering above, you can find:

  1. When a value changes to a new value, it is a gradient The process;

  2. There is a vertical line at the end of the arc, which serves as the pointer of the dashboard. When the value of the dashboard changes, there is a flexible animation effect.

At first, I used Echarts to implement the dashboard, but it could not meet the above two requirements. So I later changed to using D3.js.

D3.js can perfectly customize charts and perfectly meet our needs in terms of details.

Initialize the dashboard

1. First define an svg element:

<svg></svg>

Then, declare some variables for initialization:

var width=80, 
  height=108,  //svg的高度和宽度,也可以通过svg的width、height属性获取
  innerRadius = 22,
  outerRadius = 30, //圆弧的内外半径
  arcMin = -Math.PI*2/3,
  arcMax = Math.PI*2/3, //圆弧的起始角度和终止角度

2. Create an arc method and set all properties except endAngle. When creating an arc, pass an object containing the endAngle property to this method to calculate the SVG path for a given angle.

var arc = d3.arc()
  .innerRadius(22)
  .outerRadius(30)
  .startAngle(arcMin)

How to set the arc angle?

Corresponding a circle to a clock, then the angle corresponding to 12 o'clock is 0, the angle at 3 o'clock clockwise is Math.PI/2, and the angle at 6 o'clock counterclockwise is -Math.PI . Therefore, the arc shape from -Math.PI*2/3 to Math.PI*2/3 is as shown in the rendering above. For more information, refer to arc.startAngle in the API documentation.

3. Get the SVG elements and convert the origin to the center of the canvas, so that we don’t need to specify their positions separately when creating arcs later

var svg = d3.select("#myGauge")
var g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

4. Add a dashboard The text (title, value, unit) in

//添加仪表盘的标题
g.append("text").attr("class", "gauge-title")
  .style("alignment-baseline", "central") //相对父元素对齐方式
  .style("text-anchor", "middle") //文本锚点,居中
  .attr("y", -45)  //到中心的距离
  .text("CPU占用率");
//添加仪表盘显示的数值,因为之后还要更新,所以声明一个变量
var valueLabel = g.append("text").attr("class", "gauge-value")
  .style("alignment-baseline", "central") //相对父元素对齐方式
  .style("text-anchor", "middle") //文本锚点,居中
  .attr("y", 25)  //到中心的距离
  .text(12.65); 
//添加仪表盘显示数值的单位      
g.append("text").attr("class", "gauge-unity")
  .style("alignment-baseline", "central") //相对父元素对齐方式
  .style("text-anchor", "middle") //文本锚点,居中
  .attr("y", 40)  //到中心的距离
  .text("%");

Compared with the Canvas drawn by Echarts, a very important advantage of the SVG image produced by D3 is that the SVG style can be defined with CSS. For example, the style of the dashboard title here is as follows:

.gauge-title{
  font-size: 10px;
  fill: #A1A6AD;
}

5. Add a background arc

//添加背景圆弧
var background = g.append("path")
  .datum({endAngle:arcMax}) //传递endAngle参数到arc方法
  .style("fill", "#444851")
  .attr("d", arc);

6. Add an arc representing the percentage, where percentage is the percentage to be expressed, from 0 to decimals of 1.

//计算圆弧的结束角度
var currentAngle = percentage*(arcMax-arcMin) + arcMin
//添加另一层圆弧,用于表示百分比
var foreground = g.append("path")
  .datum({endAngle:currentAngle})
  .style("fill", "#444851")
  .attr("d", arc);

7. Add a pointer mark at the end of the arc

var tick = g.append("line")
  .attr('class', 'gauge-tick')
  .attr("x1", 0)
  .attr("y1", -innerRadius)
  .attr("x2", 0)
  .attr("y2", -(innerRadius + 12)) //定义line位置,默认是在圆弧正中间,12是指针的长度
  .style("stroke", "#A1A6AD")
  .attr('transform', 'rotate('+ angleToDegree(currentAngle) +')')

The parameter in rotate is the degree, and Math.PI corresponds to 180, so you need to customize an angleToDegree method to convert the currentAngle.

At this point, an SVG dashboard has been created, but it is static. So how to update this dashboard?

Update Dashboard

Need to update: arc representing the new percentage; the value below the arc.

Modifying the value below the arc is very simple:

valueLabel.text(newValue)

Updating the arc is a little more troublesome. The specific idea is: modify the endAngle of the arc, and modify the transform value of the pointer at the end of the arc.

During the implementation process, the API that needs to be used:

selection.transition: https://github.com/d3/d3-transition/blob/master/ README.md#selection_transition
transition.attrTween:https://github.com/d3/d3-transition/blob/master/README.md#transition_attrTween
d3.interpolate:https://github.com/ d3/d3-interpolate/blob/master/README.md#interpolate

1. Update the arc, where angle is the end angle of the new arc.

//更新圆弧,并且设置渐变动效
foreground.transition()
  .duration(750)
  .ease(d3.easeElastic)  //设置来回弹动的效果
  .attrTween("d", arcTween(angle));

arcTween method is defined as follows. It returns a tween (gradient) animation method of the d attribute, which makes an arc gradient from the current angle to a new angle.

arcTween(newAngle) {
  let self=this
  return function(d) {
    var interpolate = d3.interpolate(d.endAngle, newAngle); //在两个值间找一个插值
    return function(t) {
      d.endAngle = interpolate(t);  //根据 transition 的时间 t 计算插值并赋值给endAngle
      return arc(d); //返回新的“d”属性值
    }; 
  };
}

For a more detailed description of this method, please refer to the comments in Arc Tween.

2. The principle of updating the pointer at the end of the arc is the same as above, where oldAngle is the end angle of the old arc.

//更新圆弧末端的指针标记,并且设置渐变动效      
tick.transition()
  .duration(750)
  .ease(d3.easeElastic)  //设置来回弹动的效果
  .attrTween('transform', function(){ //设置“transform”属性的渐变,原理同上面的arcTween方法
    var i = d3.interpolate(angleToDegree(oldAngle), angleToDegree(newAngle));  //取插值
    return function(t) {
      return 'rotate('+ i(t) +')'
    };
  })

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of vue todo-list component case

Detailed steps of AngularJS application modularization

JS insert DOM node (with code)

The above is the detailed content of D3.js implements dynamic dial effect. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft