原始数据

1
2
3
var tags = [
["java", 585413], ["javascript", 557407],...,["unit-testing", 23249]
];

页面结构

1
2
<div id="cloud"></div>
<div id="details"></div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#cloud {
width: 640px;
height: 450px;
position: relative;
border-radius: 3px;
border: 1px solid #d0d0d0;
}
#cloud span {
cursor: pointer;
}
#details {
width: 640px;
text-align: center;
line-height: 2em;
margin-top: 0.5em
}

图表绘制

1
2
3
4
WordCloud(document.getElementById('cloud'), {
list: tags.map(function(word) {
return [word[0], Math.round(word[1] / 5500)];
})});

添加交互

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var clicked = function(ev) {
let info = '';
if (ev.target.nodeName === 'SPAN') {
let tag = ev.target.textContent;
let clickedTag;
let flag = tags.some(function(el) {
if (el[0] === tag) {
clickedTag = el;
return true;
}
return false;
});
if (flag) {
info = 'There were ' + clickedTag[1] + ' StackOverflow questions tagged \"' + tag + '\"';
document.getElementById('details').innerText = info;
} else {
document.getElementById('details').innerText = '';
}
}
}
document.getElementById('cloud').addEventListener('click', clicked);

结果展示

wordcloud