-
Notifications
You must be signed in to change notification settings - Fork 0
/
d3-canvas-worker-transfer.html
123 lines (102 loc) · 2.8 KB
/
d3-canvas-worker-transfer.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
123
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="./js/d3.min.js"></script>
<title>demo--</title>
</head>
<body>
<canvas id="myCanvas" width="5000" height="5000" style="display: block;">
您的浏览器不支持 HTML5 canvas 标签。
····</canvas>
<script>
const width = 5000
height = 5000
color = d3.scaleOrdinal(d3.schemeCategory10)
var canvas = document.getElementById('myCanvas')
var context = canvas.getContext("2d")
function ticked(data) {
context.clearRect(0, 0, width, height);
context.beginPath();
let links = data.links
let nodes = data.nodes;
for (let i = 0; i < links.length / 2; i++) {
context.moveTo(nodes[links[i * 2]].x / 2, nodes[links[i * 2]].y / 2);
context.lineTo(nodes[links[i * 2 + 1]].x / 2, nodes[links[i * 2 + 1]].y / 2);
}
context.strokeStyle = "#aaa";
context.stroke();
for (const node of data.nodes) {
context.beginPath();
drawNode(node)
context.fillStyle = color(1);
context.fill();
}
}
function drawNode(d) {
// 画点
context.moveTo(d.x / 2 + 3, d.y / 2);
context.arc(d.x / 2, d.y / 2, 3, 0, 2 * Math.PI);
}
// 读数据
d3.json("../data/dataset2/1-1.json").then(function (data) {
//DEFINE
let nodeInfoMap = {},
e = 0,
linkInfoMap = {};
//创建node地图
data.nodes.forEach(n => {
nodeInfoMap[n.id] || (nodeInfoMap[n.id] = {
index: e,
id: n.id
}, e++)
})
//创建i,linkbuffer的原型
let i = [];
data.links.forEach(e => {
let r = "".concat(e.source, "-").concat(e.target); //每条边对应的唯一id
linkInfoMap[r] || (i.push(nodeInfoMap[e.source].index, nodeInfoMap[e.target].index),
linkInfoMap[r] = {
id: r
})
});
//得到linkbuffer
let linkBuffer = new Int32Array(i);
//数据IO计时
let end, count = 0
//worker创建
const worker = new Worker('./js/d3-canvas-worker-transfer.js')
//message创建
let d = {
nodesCount: Object.keys(nodeInfoMap).length,
linksBuffer: linkBuffer.buffer
}
//worker
worker.postMessage(d, [d.linksBuffer])
worker.onmessage = e => {
// if(count!=10){
// count++;
// }if(count==10){
// count++
// end= new Date()
// // console.log(end-e.data.start);
// }
let nodes = [];
let links = [];
let tickNodes = new Int32Array(e.data.nodes); //得到了所有nodes的平铺x,y坐标
for (let i = 0; i < tickNodes.length / 2; i++) {
nodes.push({
x: tickNodes[i * 2],
y: tickNodes[i * 2 + 1]
})
}
let tickdata = {
nodes: nodes,
links: i
}
ticked(tickdata);
}//worker.onmessage()
})//d3.data.then();
</script>
</body>
</html>