-
Notifications
You must be signed in to change notification settings - Fork 1
/
word-cloud.js
91 lines (78 loc) · 2.53 KB
/
word-cloud.js
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
var fill = d3.scale.category20b();
var w = window.innerWidth,
h = window.innerHeight;
var max,
fontSize;
var layout = d3.layout.cloud()
.timeInterval(Infinity)
.size([w, h])
.fontSize(function(d) {
return fontSize(+d.value);
})
.text(function(d) {
return d.key;
})
.on("end", draw);
var svg = d3.select("#vis").append("svg")
.attr("width", w)
.attr("height", h);
var vis = svg.append("g").attr("transform", "translate(" + [w >> 1, h >> 1] + ")");
update();
if(window.attachEvent) {
window.attachEvent('onresize', update);
}
else if(window.addEventListener) {
window.addEventListener('resize', update);
}
function draw(data, bounds) {
var w = window.innerWidth,
h = window.innerHeight;
svg.attr("width", w).attr("height", h);
scale = bounds ? Math.min(
w / Math.abs(bounds[1].x - w / 2),
w / Math.abs(bounds[0].x - w / 2),
h / Math.abs(bounds[1].y - h / 2),
h / Math.abs(bounds[0].y - h / 2)) / 2 : 1;
var text = vis.selectAll("text")
.data(data, function(d) {
return d.text.toLowerCase();
});
text.transition()
.duration(1000)
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.style("font-size", function(d) {
return d.size + "px";
});
text.enter().append("text")
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.style("font-size", function(d) {
return d.size + "px";
})
.style("opacity", 1e-6)
.transition()
.duration(1000)
.style("opacity", 1);
text.style("font-family", function(d) {
return d.font;
})
.style("fill", function(d) {
return fill(d.text.toLowerCase());
})
.text(function(d) {
return d.text;
});
vis.transition().attr("transform", "translate(" + [w >> 1, h >> 1] + ")scale(" + scale + ")");
}
function update() {
layout.font('impact').spiral('archimedean');
fontSize = d3.scale['sqrt']().range([10, 100]);
if (data.length){
fontSize.domain([+data[data.length - 1].value || 1, +data[0].value]);
}
layout.stop().words(data).start();
}