🚀 For deeper insights into word frequency and character analysis, you can also explore the Word Counter Tool, a free online resource that complements your word cloud project perfectly.
What Is a Word Cloud and Why Is It Useful?
A word cloud, also known as a tag cloud or text cloud, is a visual representation of text data where the size of each word reflects its frequency or importance within a given body of text. The more often a word appears, the larger and bolder it is displayed in the cloud.
Why Word Clouds Are Useful?
Quick Insights: They instantly highlight the most common words in a dataset, making it easy to spot key themes or ideas.
Enhanced UX/UI: They add visual interest to otherwise static content. A well-designed word cloud can make a page feel dynamic and personalized, especially when built from user input.
Lightweight Data Visualization: Unlike complex charts or graphs, word clouds are easy to implement and don't require heavy libraries.
The Markup
The HTML structure includes a <textarea> for user input and a <canvas> element to render the word cloud. When the user enters text and clicks the button, the cloud is generated dynamically based on word frequency.
Additionally, the WordCloud2.js CDN has been included in the <head> section to enable the word cloud functionality.
<!DOCTYPE html> <html lang="en"> <head> <title>Word Cloud example using JavaScript</title> <script src="https://cdn.jsdelivr.net/npm/wordcloud@1.1.0/src/wordcloud2.js"></script> </head> <body> <textarea id="ta" rows="6" cols="50" placeholder="Enter text here..."></textarea><br> <button onclick="generateWordCloud()">Generate Word Cloud</button> <canvas id="canvas" width="500" height="500"></canvas> </body> </html>
The Script for Word Cloud
<script> function generateWordCloud() { const text = document.getElementById('ta').value.trim(); // The text (or data) from the textarea. if (!text) return; // Convert all characters into lower case. Next, remove unwanted characters. // Split the text into an array of words. const words = text .toLowerCase() .replace(/[^\w\s]/g, '') .split(/\s+/); // Loop through each word in the "words" array and Count the frequency of each word in an array. const frequencyMap = {}; words.forEach(word => { if (word) frequencyMap[word] = (frequencyMap[word] || 0) + 1; }); // console.log(frequencyMap); // Transform the frequencyMap object into a format that the WordCloud.js library can understand and render. const entries = Object.entries(frequencyMap).map(([word, freq]) => [word, freq]); // Render (draw) the cloud inside the Canvas element with the entries (array of words and word frequency). WordCloud(document.getElementById('canvas'), { list: entries, gridSize: 8, weightFactor: 10, fontFamily: 'Arial', color: 'random-dark', backgroundColor: '#fff', rotateRatio: 0.5, shape: 'cloud', // The Built-in cloud shape. drawOutOfBound: false }); } </script> </html>
How the Code Works?
1) Extracting Text from the Textarea: The code starts by grabbing the text that the user types into the <textarea> element and stores it in a variable called text. This is the raw input that will be used to build the word cloud.
2) Cleaning and Normalizing the Text: It then converts all the characters to lowercase using .toLowerCase(). This ensures that words like "JavaScript" and "javascript" are treated as the same.
Next, it removes any unwanted characters, like punctuation marks or symbols, so that only actual words remain. This is done using a regular expression.
3) Counting Word Frequency: The cleaned text is split into individual words and stored in an array. The code then loops through each word and counts how many times it appears. These counts are stored in an object called frequencyMap.
🚀 For deeper insights into word frequency and character analysis, you can also explore the Word Counter Tool, a free online resource that complements your word cloud project perfectly.
4) Preparing Data for the Word Cloud: The frequency map is converted into a list of word frequency pairs. This format is required by the "WordCloud.js" library to know which words to display and how big each one should be.
5) Rendering the Word Cloud: Finally, the WordCloud() function is called to draw the cloud inside the <canvas> element. This function takes several options to customize how the cloud looks:
• list: The array of [word, frequency] pairs that tells the cloud which words to show and how often they appear.
• gridSize: Controls the spacing between words. Smaller values pack words closer together.
• weightFactor: Determines how big each word appears based on its frequency. Higher values make frequent words much larger.
• fontFamily: Sets the font style for the words (e.g., Arial, Verdana).
• color: Defines the color of each word. 'random-dark' gives each word a random dark shade.
• backgroundColor: Sets the background color of the canvas.
• rotateRatio: Controls how many words are rotated at an angle. A value of 0.5 means about half the words will be rotated.
• shape: Defines the overall shape of the cloud (e.g., 'cloud', 'circle', 'star').
• drawOutOfBound: If set to false, it prevents words from being drawn outside the canvas area.
👉 In a word cloud generated, each word's size is determined by its frequency, the more often a word appears in the input text, the larger it will be displayed. This is controlled by the weightFactor property, which scales the font size based on the word’s count.
The "color" of each word is defined separately using the color option. color: 'random-dark'
Increase Font Size of Each Word in the Cloud
To increase the font size of each word in your word cloud, you can adjust the weightFactor property in the WordCloud configuration. This property determines how large each word appears based on its frequency.
For example, "weightFactor: 20,".
Add a Tooltip Showing Word Count on Hover
To add a tooltip showing the word count when hovering over each word in your word cloud, you can use the hover callback provided by the WordCloud.js library. Here's how you can modify the WordCloud configuration to include tooltips.
The "tooltip" will follow the mouse and display the word and its frequency when hover over a word in the "cloud".
<head> <script src="https://cdn.jsdelivr.net/npm/wordcloud@1.1.0/src/wordcloud2.js"></script> </head> <body> <textarea id="ta" rows="6" cols="50" placeholder="Enter text here..."></textarea><br> <button onclick="generateWordCloud()">Generate Word Cloud</button> <canvas id="canvas" width="500" height="500"></canvas> <div id="tooltip" style="position: absolute; background: rgba(0, 0, 0, 0.75); color: white; padding: 5px 10px; border-radius: 4px; font-size: 14px; pointer-events: none; display: none; z-index: 1000;"> </div> </body> <script> function generateWordCloud() { const text = document.getElementById('ta').value.trim(); if (!text) return; const words = text .toLowerCase() .replace(/[^\w\s]/g, '') .split(/\s+/); const frequencyMap = {}; words.forEach(word => { if (word) frequencyMap[word] = (frequencyMap[word] || 0) + 1; }); const entries = Object.entries(frequencyMap).map(([word, freq]) => [word, freq]); WordCloud(document.getElementById('canvas'), { list: entries, gridSize: 8, weightFactor: 20, fontFamily: 'Arial', color: 'random-dark', backgroundColor: '#fff', rotateRatio: 0.5, shape: 'cloud', drawOutOfBound: false, // Tooltip on hover. hover: function(item, dimension, event) { if (item) { const tooltip = document.getElementById('tooltip'); tooltip.style.left = event.pageX + 10 + 'px'; tooltip.style.top = event.pageY + 10 + 'px'; tooltip.style.display = 'block'; tooltip.innerText = `${item[0]}: ${item[1]} times`; } else { document.getElementById('tooltip').style.display = 'none'; } } }); } </script>
Word Cloud with Tooltip:
Conclusion
Creating a word cloud is a fun and visual way to explore your writing. With WordCloud.js and a bit of JavaScript, you've learned how to turn plain text into a colorful snapshot of your most-used words. It's a great starting point for beginners who want to dive into web development or text analysis.
To take your project further, you can use tools like The Word Counter. It's a free, beginner-friendly site that instantly counts words, characters, and even shows word frequency. It now includes a built-in word cloud feature, perfect for previewing your text before coding or optimizing content for SEO and readability.