Animated text sphere in JavaScript using TagCloud.js

Animated text sphere in JavaScript using TagCloud.js

I needed a sphere of rotating words for one of my projects. So, I scoured the internet for that. Hard luck didn't find anything suitable. I did find one pen on codepen which had a very complicated JavaScript code, difficult to understand. That is when I came across TagCloud.js by Cong Min. Check out his GitHub profile.

TagCloud.js is a standalone JavaScript library for rendering an animated, interactive, 3D sphere tag cloud from an array text strings you provide.

Read the documentation here.

text-sphere

Now, how to create one on your own:

HTML

  1. Create a container to hold the tag cloud.
<span class="content"></span>
  1. Import the TagCloud.js script CDN in the document
<script src="https://cdn.jsdelivr.net/npm/TagCloud@2.2.0/dist/TagCloud.min.js"></script>

CSS

  1. Add your own CSS styles to the tag cloud.
.tagcloud {
    font-family: 'Poppins', sans-serif;  
    font-size: 20px;
    font-weight: 650;
    margin-left: 30%;
  }
  .tagcloud--item:hover {
    color: #36454F;
  }

JavaScript

  1. Define your tags in a JS array.
const myTags = [
    'JavaScript', 'CSS', 'HTML',
    'C', 'C++', 'React',
    'Python', 'Java', 'git',
    'django', 'Node.js', 'OpenCV',
    'GCP', 'MySQL', 'jQuery',
];
  1. Render a default tag cloud.
var tagCloud = TagCloud('.content', myTags);
  1. Config the tag cloud by overriding the default parameters
var tagCloud = TagCloud('.content', myTags,{

  // radius in px
  radius: 300,

  // animation speed
  // slow, normal, fast
  maxSpeed: 'fast',
  initSpeed: 'fast',

  // 0 = top
  // 90 = left
  // 135 = right-bottom
  direction: 135,

  // interact with cursor move on mouse out
  keep: true

});

This creates a basic cloud of words. If you want to change the color of words randomly after each reload, add this small JavaScript code at the end.

var colors = ['#34A853', '#FBBC05', '#4285F4', '#7FBC00', 'FFBA01', '01A6F0'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
document.querySelector('.content').style.color = random_color;

If done correctly, you should get this result 👇

And that's it, very simple and straightforward😉✌ Thanks for reading!!