-
Notifications
You must be signed in to change notification settings - Fork 4
/
2.interaction.html
122 lines (109 loc) · 2.92 KB
/
2.interaction.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Interaction Demo</title>
<script src="js/d3.v3.js"></script>
<style>
svg {
width: 600px;
height: 500px;
border: 1px;
border-color: gray;
border-style: solid;
}
text {
text-anchor: middle;
}
circle {
fill: orange;
stroke: orange;
fill-opacity: 0.5;
}
button {
margin-bottom: 4px;
}
</style>
</head>
<body>
<h1>Interaction Demo</h1>
<div id="graphArea">
</div>
<script>
let currentIndex = 0
let dataSource = [
['中国', [30, 45, 88, 23]],
['美国', [40, 48, 72, 100, 34]],
['日本', [10, 33, 26]],
]
let lineLength = 400
// 创建切换数据按钮和监听处理
d3.select('#graphArea').append('button').text('切换')
.on('click', function () {
currentIndex++
if (currentIndex == dataSource.length) {
currentIndex = 0
}
let circle = svg.select('g').selectAll('circle').data(dataSource[currentIndex][1])
circle.exit().remove()
circle.enter().append('circle')
.attr('r', 0)
.on('mouseover', function () {
d3.select(this).transition()
.duration(300)
.style('fill-opacity', .8)
})
.on('mouseout', function () {
d3.select(this).transition()
.duration(300)
.style('fill-opacity', .5)
})
circle.transition().duration(500)
.attr('cx', (d, i) => {
let spacing = lineLength / dataSource[currentIndex][1].length
return 100 + i * spacing
})
.attr('cy', 250)
.attr('r', (d) => {
return d
})
svg.select('text').text(dataSource[currentIndex][0])
})
d3.select('#graphArea').append('br')
//创建svg
let svg = d3.select('#graphArea').append('svg')
//创建标题文本
svg.append('text').attr('x', 250).attr('y', 50).text(dataSource[currentIndex][0])
svg.append('line')
.attr('x1', 40)
.attr('y1', 250)
.attr('x2', 560)
.attr('y2', 250)
.attr('stroke', '#ddd')
//创建圆
svg.append('g').selectAll('circle')
.data(dataSource[currentIndex][1])
.enter()
.append('circle')
.attr('cx', (d, i) => {
let spacing = lineLength / dataSource[currentIndex][1].length
return 100 + i * spacing
})
.attr('cy', 250)
.attr('r', (d) => {
return d
})
.on('mouseover', function () {
d3.select(this).transition()
.duration(300)
.style('fill-opacity', .8)
})
.on('mouseout', function () {
d3.select(this).transition()
.duration(300)
.style('fill-opacity', .5)
})
//TODO 切换到d3.v5
</script>
</body>
</html>