Skip to content

Instantly share code, notes, and snippets.

Created November 6, 2016 13:18
Show Gist options
  • Save lorenzopub/820bec1dafa6a5cd11aa23c1268edcbf to your computer and use it in GitHub Desktop.
Save lorenzopub/820bec1dafa6a5cd11aa23c1268edcbf to your computer and use it in GitHub Desktop.
Animated d3 word cloud
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<script src=""></script>
<script src=""></script>
//Simple animated example of d3-cloud -
//Based on
// Encapsulate the word cloud functionality
function wordCloud(selector) {
var fill = d3.scale.category20();
//Construct the word cloud's SVG element
var svg ="svg")
.attr("width", 500)
.attr("height", 500)
.attr("transform", "translate(250,250)");
//Draw the word cloud
function draw(words) {
var cloud = svg.selectAll("g text")
.data(words, function(d) { return d.text; })
//Entering words
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr('font-size', 1)
.text(function(d) { return d.text; });
//Entering and existing words
.style("font-size", function(d) { return d.size + "px"; })
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
.style("fill-opacity", 1);
//Exiting words
.style('fill-opacity', 1e-6)
.attr('font-size', 1)
//Use the module pattern to encapsulate the visualisation code. We'll
// expose only the parts that need to be public.
return {
//Recompute the word cloud for a new set of words. This method will
// asycnhronously call draw when the layout has been computed.
//The outside world will need to call this function, so make it part
// of the wordCloud return value.
update: function(words) {[500, 500])
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.fontSize(function(d) { return d.size; })
.on("end", draw)
//Some sample data -
var words = [
"Feliz Cumpleaños Deisy, sabes que te quiero muchísimo, un fuerte abrazo"
//Prepare one of the sample sentences by removing punctuation,
// creating an array of words and computing a random size attribute.
function getWords(i) {
return words[i]
.replace(/[!\.,:;\?]/g, '')
.split(' ')
.map(function(d) {
return {text: d, size: 10 + Math.random() * 60};
//This method tells the word cloud to redraw with a new set of words.
//In reality the new words would probably come from a server request,
// user input or some other source.
function showNewWords(vis, i) {
i = i || 0;
vis.update(getWords(i ++ % words.length))
setTimeout(function() { showNewWords(vis, i + 1)}, 2000)
//Create a new instance of the word cloud visualisation.
var myWordCloud = wordCloud('body');
//Start cycling through the demo data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment