### Install wordcloud2.js via npm Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/README.md This command installs the wordcloud2.js library using npm, making it available for use in your project. ```bash npm install wordcloud ``` -------------------------------- ### wordcloud2.js Data Format Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/README.md This example shows the expected format for the `list` parameter when using wordcloud2.js. It's an array where each element is a two-item array containing a word (string) and its corresponding weight (number). ```javascript const list = [['foo', 12], ['bar', 6]]; ``` -------------------------------- ### Stop Rendering Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md Stops the word cloud rendering process. This is useful for optimizing performance in frameworks like React. It should be called within a cleanup function, for example, using `useEffect`'s return function. ```javascript useEffect(() => { // ... other logic return () => { // stop the renderring WordCloud.stop(); }; }, [deps]); ``` -------------------------------- ### Simple Usage of wordcloud2.js Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/README.md This JavaScript snippet demonstrates the basic usage of wordcloud2.js. It initializes a word cloud on a specified canvas element using a predefined list of words and their associated weights. The `list` parameter expects an array of [word, weight] pairs. ```javascript WordCloud(document.getElementById('my_canvas'), { list: list } ); ``` -------------------------------- ### Testing wordcloud2.js with Grunt Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/README.md These Grunt commands are used for testing the wordcloud2.js library. `grunt test` runs all tests, while `grunt compare --base-commit=gh-pages` compares the current changes against the `gh-pages` branch. ```bash npm install grunt test grunt compare --base-commit=gh-pages ``` -------------------------------- ### WordCloud Usage and Options Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md Initializes a word cloud using the `WordCloud` function. It takes the target DOM element(s) and an options object for customization. The `elements` parameter can be a single DOM element or an array of elements. If a `` element is provided, the word cloud is drawn on it; otherwise, `` elements are created. ```APIDOC WordCloud(elements, options); -- Parameters -- elements: DOM Element or array of DOM Elements. The target for rendering the word cloud. options: Object. Configuration options for the word cloud. -- Options -- ### Presentation * list: Array[Array]. List of words and their sizes, e.g., [['foo', 12], ['bar', 6]]. Can include additional data for callbacks. * fontFamily: String. Font family to use. * fontWeight: String | Function. Font weight (e.g., 'normal', 'bold', '600') or a callback function `(word, weight, fontSize, extraData)`. * color: String | Function. Text color (CSS color, 'random-dark', 'random-light') or a callback function `(word, weight, fontSize, distance, theta)`. For DOM clouds, can be `null` to disable hardcoding. * classes: String | Function. CSS class for span elements in DOM clouds, or a callback function `(word, weight, fontSize, extraData)`. No effect on canvas clouds or if `null`. * minSize: Number. Minimum font size to draw. * weightFactor: Number | Function. Multiplier for word size or a function to calculate it. * clearCanvas: Boolean. Whether to clear the canvas with the background color before drawing. * backgroundColor: String. Background color of the canvas. ### Dimension * gridSize: Number. Grid size in pixels for word placement. * origin: Array[Number]. The [x, y] origin of the word cloud. * drawOutOfBound: Boolean. Allows words to be partially drawn outside the canvas. * shrinkToFit: Boolean. Shrinks words to fit within the canvas. May reduce word weight. ### Mask * drawMask: Boolean. Visualizes the grid by drawing mask squares. * maskColor: String. Color of the mask squares. * maskGapWidth: Number. Width of the gaps between mask squares. ### Timing * wait: Number. Delay in milliseconds before drawing the next item. * abortThreshold: Number. Time in milliseconds after which rendering is aborted if it blocks the browser. * abort: Function. Callback function called when rendering is aborted. ### Rotation * minRotation: Number. Minimum rotation angle in radians. * maxRotation: Number. Maximum rotation angle in radians. * rotationSteps: Number. Number of discrete rotation angles to use. ``` -------------------------------- ### wordcloud2.js API Documentation Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/index.html Details the available options and configurations for wordcloud2.js, covering dimensions, masking, and web font integration. ```APIDOC wordcloud2.js API Documentation This document outlines the various options available for configuring wordcloud2.js. **Core Functionality:** wordcloud2.js renders tag clouds on HTML5 canvas or HTML elements. **Configuration Options:** * **width**: (Number) The width of the canvas. Leave blank to use page width. * **height**: (Number) The height of the canvas. Leave blank to use 0.65x of the width. * **density**: (Number) Device pixel density (dppx). Adjusts weight, grid size, and canvas pixel size for high-resolution displays. * **mask**: (Image Element or URL) An image used as a mask. The white area of the image will be excluded from drawing. When a mask is used, `clearCanvas` is automatically set to `false`. * **shape**: (String) The shape of the cloud to grow. This option applies when a mask is used. * **clearCanvas**: (Boolean) Whether to clear the canvas before drawing. Defaults to `true`. * **extraWebFontCSS**: (String) URL to a CSS file containing extra web fonts (e.g., from Google Web Fonts). Re-run the cloud generation if fonts don't load correctly. **Usage Example (JavaScript Object):** ```javascript var options = { width: 800, height: 600, density: 2, mask: 'path/to/your/mask.png', shape: 'circle', extraWebFontCSS: 'https://fonts.googleapis.com/css?family=Open+Sans' }; WordCloud(document.getElementById('my_canvas'), { list: my_word_list, ...options }); ``` **Note:** Refer to the [API document](https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md) for a comprehensive list of all available options and their detailed descriptions. ``` -------------------------------- ### Matomo Analytics Integration Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/index.html Configures and integrates Matomo (formerly Piwik) for website analytics, tracking page views and link clicks. ```javascript var _paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//stats.timdream.org/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '6']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); ``` -------------------------------- ### CSS Styling for wordcloud2.js Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/index.html Provides essential CSS for styling the wordcloud2.js presentation, including layout, responsiveness, and hover effects for individual words. ```css body { padding-top: 60px; } *[hidden] { display: none; } #canvas-container { overflow-x: auto; overflow-y: visible; position: relative; margin-top: 20px; margin-bottom: 20px; } .canvas { display: block; position: relative; overflow: hidden; } .canvas.hide { display: none; } #html-canvas > span { transition: text-shadow 1s ease, opacity 1s ease; -webkit-transition: text-shadow 1s ease, opacity 1s ease; -ms-transition: text-shadow 1s ease, opacity 1s ease; } #html-canvas > span:hover { text-shadow: 0 0 10px, 0 0 10px #fff, 0 0 10px #fff, 0 0 10px #fff; opacity: 0.5; } #box { pointer-events: none; position: absolute; box-shadow: 0 0 200px 200px rgba(255, 255, 255, 0.5); border-radius: 50px; cursor: pointer; } textarea { height: 20em; } #config-option { font-family: monospace; } select { width: 100%; } #loading { animation: blink 2s infinite; -webkit-animation: blink 2s infinite; } @-webkit-keyframes blink { 0% { opacity: 1; } 100% { opacity: 0; } } @keyframes blink { 0% { opacity: 1; } 100% { opacity: 0; } } ``` -------------------------------- ### Feature Detection Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md Checks if the browser supports the necessary functionalities for wordcloud2.js to run. Returns `false` if not supported. ```javascript WordCloud.isSupported ``` -------------------------------- ### QUnit Test Styling Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/test/index.html Styles for the QUnit test runner interface, including general test item styling and specific styling for canvas elements used in tests. It also includes hover effects to enlarge the canvas and visual cues for passing or failing tests. ```css #qunit-tests > li::after { content: ''; display: block; clear: both; } #qunit-tests > li > canvas { float: right; margin-left: 20px; border: 4px solid #ccc; width: 150px; /* http://lea.verou.me/css3patterns/#checkerboard */ background-color: #eee; background-image: linear-gradient(45deg, #ccc 25%, transparent 25%, transparent 75%, #ccc 75%, #ccc), linear-gradient(45deg, #ccc 25%, transparent 25%, transparent 75%, #ccc 75%, #ccc); background-size: 60px 60px; background-position: 0 0, 30px 30px; } #qunit-tests > li:hover > canvas { width: 300px; } #qunit-tests > li > canvas:not(.reference) { cursor: pointer; } #qunit-tests > li.fail > canvas:not(.reference) { border-color: #EE5757; } #qunit-tests > li.pass > canvas:not(.reference) { border-color: #C6E746; } ``` -------------------------------- ### wordcloud2.js Custom DOM Events Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md wordcloud2.js emits custom DOM events that can be listened to for managing the word cloud lifecycle. These include 'wordcloudstart', 'wordclouddrawn', 'wordcloudstop', and 'wordcloudabort'. Listening to 'wordcloudstart' allows for immediate cancellation of the drawing process. ```javascript const canvas = document.getElementById('myWordCloud'); canvas.addEventListener('wordcloudstart', () => { console.log('Word cloud drawing started.'); }); canvas.addEventListener('wordclouddrawn', () => { console.log('Word cloud has been drawn.'); }); canvas.addEventListener('wordcloudstop', () => { console.log('Word cloud drawing stopped.'); }); canvas.addEventListener('wordcloudabort', () => { console.log('Word cloud drawing aborted.'); }); // To cancel immediately: // canvas.addEventListener('wordcloudstart', (event) => { // event.preventDefault(); // Stops the drawing process // }); ``` -------------------------------- ### wordcloud2.js Interactive Configuration Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md Enables interactive features for the word cloud. The 'hover' callback is triggered when the cursor enters or leaves a word, receiving the word item, its dimensions, and the event object. The 'click' callback is invoked when a word is clicked, also providing the word item, dimensions, and the event object. ```javascript { "hover": function(item, dimension, event) { /* ... */ }, "click": function(item, dimension, event) { /* ... */ } } ``` -------------------------------- ### Generate Polar Equation from Image Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/shape-generator.html This JavaScript code snippet processes an image to determine its approximate polar equation. It reads pixel data, traces the boundary of a shape from the center, and calculates the distance to the boundary for different angles. The output is a JavaScript function that can be used to represent the shape in polar coordinates. Requires an HTML file with an input element with id 'file' for file selection and an element with id 'result' to display the output function. ```javascript var img, url; window.onload = function() { // DOM File object selected var file = document.getElementById('file').files[0]; if (file) run(); } function run() { // DOM File object selected var file = document.getElementById('file').files[0]; url = window.URL.createObjectURL(file); img = new Image(); img.src = url; img.onload = readPixels; } function readPixels() { window.URL.revokeObjectURL(url); var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; document.body.appendChild(canvas); var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, img.width, img.height); var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); var mask = new Uint8Array(imageData.data.length / 4); var width = canvas.width; var height = canvas.height; var o = [(img.width / 2) | 0, (img.height / 2) | 0]; var d = window.d = []; // paint red on the center pixel (not really visible) imageData.data[(o[1] * width + o[0]) * 4] = 254; for (var theta = 0; theta < 2 * Math.PI; theta += 0.01) { var dx = 1 * Math.cos(theta); var dy = -1 * Math.sin(theta); var i = 0; var x = o[0]; var y = o[1]; var intX = x; var intY = y; while (true) { x += dx; y += dy; intX = x | 0; intY = y | 0; if (intY < 0 || intY > canvas.height || intX < 0 || intX > width) { break; } var ptr = (intY * width + intX) * 4; var tone = imageData.data[ptr] + imageData.data[ptr + 1] + imageData.data[ptr + 2]; var alpha = imageData.data[ptr + 3]; // draw a green line all the way until the boundary imageData.data[ptr] = 0; // R imageData.data[ptr + 1] = 254; // G imageData.data[ptr + 2] = 0; // B imageData.data[ptr + 3] = 254; // A // are we there at the boundary? if (alpha < 128 || tone > 128 * 3) { d.push(i); break; } else { i++; } } } ctx.putImageData(imageData, 0, 0); var max = d.reduce(function(prev, curr) { return Math.max(prev, curr); }); var resultText = 'function(theta) {\n' + ' var max = ' + max + ';\n' + ' var leng = ' + JSON.stringify(d) + ';\n\n' + ' return leng[(theta / (2 * Math.PI)) * leng.length | 0] / max;\n' + '}\n'; var result = document.getElementById('result'); result.textContent = resultText; } ``` -------------------------------- ### Randomness Options Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md Controls the randomness of the word cloud generation. The `shuffle` option randomizes the order of words, leading to different results each time. The `rotateRatio` determines the probability of words being rotated. ```APIDOC -- Randomness -- * shuffle: Boolean. Shuffles the points to draw, resulting in different outputs for the same input. * rotateRatio: Number. Probability for a word to rotate. Set to 1 to always rotate. ``` -------------------------------- ### wordcloud2.js Shape Configuration Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md Configures the shape of the word cloud. Supports predefined shapes like 'circle', 'cardioid', 'diamond', 'square', 'triangle-forward', 'triangle', 'pentagon', 'star', or a custom polar equation as a callback function. Also includes an ellipticity setting for controlling the shape's flatness. ```javascript { "shape": "cardioid", // or a callback function "ellipticity": 0.8 } ``` -------------------------------- ### Minimum Font Size Access Source: https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md Accesses the detected minimum font size preference of the browser, which can affect canvas rendering. This value is accessible via `WordCloud.minFontSize`. ```javascript WordCloud.minFontSize ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.