This time I will bring you D3.js to create a circular memory storage map. What are the precautions for using D3.js to create a circular memory storage map? The following is a practical case, let's take a look.
Dynamic renderings:

Dashboard renderings
If you look closely at the dynamic renderings above, you can find:
When a value changes to a new value, it is a gradual process;
There is a vertical line at the end of the arc, which serves as the pointer of the dashboard. There is a flexible animation effect when the dashboard value changes.
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; 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) +')'
};
})
At this point, we have successfully created a dynamically refreshing SVG dashboard with a beautiful introduction.
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:
Operation AngularJS from scratch to realize application modularization
Summary of JS insertion method of DOM object node
The above is the detailed content of D3.js creates a memory circular storage map. For more information, please follow other related articles on the PHP Chinese website!
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function






