Horizontally position the main word from the D3-WordCloud in the center

I am working on a WordCloud project and have utilized code from Jason Davies D3-JavaScript-WordCloud Example, which can be found at this link.

The majority of the code I have used is from a helpful tutorial in German by Lars Ebert, available at this URL. Thank you for the guidance!

After some learning, I successfully centered the first word horizontally. However, this caused a gap to appear in the Cloud where the word would have been without positioning.

My focus now is on removing this gap. Any suggestions?

Thank you in advance for any assistance provided.

var wordcloud, size = [800, 800]; //Cloud Size
var fillColor = d3.scale.category20b();

function loaded() {
    d3.layout.cloud()
        .size(size) 
        .words(words)
        .font("Impact")
        .fontSize(function(d) { return d.size;})
        .rotate(function() { return ~~(Math.random() * 2) * 90; })
        .on("end", draw)
        .start();       
}

function draw(words) {
    wordcloud = d3.select("body")
        .append("svg")
        .attr("width", size[0])
        .attr("height", size[1])
        .append("g")
        .attr("transform", "translate(" + (size[0]/2) + "," + (size[1]/2) + ")");
    wordcloud.selectAll("text")
        .data(words)
        .enter()
        .append("text")
        .style("font-size", function(d) { return d.size + "px"; })
        .style("fill", function(d) { return fillColor(d.text.toLowerCase()); })
        .attr("text-anchor", "middle")

     //Edit
    .attr("transform", function(d, i) {
        if(i == 0){
            return "translate(" + [0, 0] + ")rotate(" + 0 + ")";    //handle first element
        }else{
            return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; //handle the rest
        }
    })
    //--------------

    .text(function(d) { return d.text; });
}

Answer №1

To achieve the desired effect, apply a negative margin that matches one of the size calculations:

 wordcloud.selectAll("text")
     ...
     ...
     ...
     .style("margin-left", function(d) {return d.size + "px"})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

Is it possible to leverage the flex features of react-native in a manner similar to the row/column system of

Is it a good idea to utilize flex in react native by creating custom components that retrieve flex values? I previously used the bootstrap grid system and now I am exploring react native. Is there a way to implement this example using react-native bootstr ...

How can I convert a PHP date to a JavaScript date that works across all

I am attempting to create a JavaScript countdown timer that relies on the server time, but I'm facing difficulties in transferring PHP time to JavaScript seamlessly across different browsers. While it functions correctly in modern browsers, older ones ...

Ensuring React's setupProxy functions properly in conjunction with express.js

I've encountered an issue while trying to pass images from express to react. My express.static is correctly set up, so when I visit localhost:5000/public/images/me.jpeg, the image loads in my browser. However, when I attempt to use <img src="/publi ...

The onClick event for a q-btn does not seem to be functioning properly when used

Inside the q-btn, there is a q-checkbox. Additionally, I included a div to style the text. <q-btn flat color="blue" class="full-width no-padding" @click="tog(item)" > <q-checkbox ...

Scroll-triggered Autoplay for YouTube Videos using JQuery

Issue: I'm trying to implement a feature where a YouTube video starts playing automatically when the user scrolls to it, and stops when the user scrolls past it. Challenges Faced: I am new to JavaScript web development. Solution Attempted: I referre ...

Start the CSS3 animation in reverse right away

I am trying to achieve a "flashing" effect by adding the .shown class to my #overlay, causing the opacity to fade in for 2 seconds and then immediately reverse, fading out for another 2 seconds. After experimenting with removing the class, I found that it ...

Express route encountered an error with an undefined value

Here's the method declaration: exports.postRedisValue = function(req,res) { let keyRedis = req.body.key; let valueRedis = req.body.value; console.log(keyRedis); //displays as undefined if(keyRedis && valueRedis){ ...

changing pictures with jquery

Struggling with this code snippet: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); No matter which ...

What is the most efficient method for managing axios errors in Laravel and Vue.js?

Currently, I am developing spa web applications using Laravel as the backend and Vue.js as the frontend framework. For authentication with API, I am utilizing Laravel Passport, and for managing my application state, I am using Vuex. Initially, I created A ...

Retrieve the binary file data that was sent via Postman using Node.js/Express.js

I am currently testing file uploading in my backend system. I am using Postman to send binary data as a file in the request body, and now I need to extract this data from the POST request. req.body The above code snippet returns a binary buffer that look ...

Is it necessary to close the browser for jQuery to reload an XML document?

I've successfully used jQuery's $.ajax to retrieve an xml value in my code. However, I'm facing an issue where any changes made to the xml document are not reflected upon a browser refresh. Specifically, the new saved xml value xmlImagePath ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

ReactJs Unicode Integration with ID3 JS

I am working on a React Project that involves using an input type = "file" to upload music files. I am able to extract tags using ID3 Js, but the result is displayed in this format: https://i.stack.imgur.com/192co.png Is there a way to convert ...

Is it possible to reduce a field value in firestore after successfully submitting a form?

I have a variety of items retrieved from firestore: availability : true stocks: 100 item: item1 https://i.stack.imgur.com/hrfDu.png I am interested in reducing the stocks after submitting a form. I used the where() method to check if the selected item m ...

Issue with Material UI: Unable to utilize import statement outside of a module due to Select dependency

Hello there! Here is my query: I am currently working on a project using NextJS + React with node. Everything seems to be running smoothly, except for one issue I encounter when reloading a page with a Select component from Material UI. The relevant code ...

Assigning index values to child rows in AngularJS: a step by step guide

One of my requirements involves assigning index values to child rows. The structure includes group rows with child rows underneath. Currently, I am using ng-repeat along with $index for the children as shown below: HTML code: <table ng-repeat="nod ...

Unfortunately, CORS is preventing me from sending a POST request through AJAX

I'm currently working on integrating an API into my website. I'm attempting to send a POST request with JSON data, but I keep encountering an error code when trying to make the request. Interestingly, sending the request using curl does not pose ...

Can JavaScript be used to bypass AJAX cookies?

Is there a way in JavaScript to programmatically ignore server-sent cookies without adjusting browser settings? We have implemented plugins on our web server that periodically update our security cookie, resulting in compatibility issues with certain URLs ...

Periodically transmit information to a Google Script web application

I am currently working on a Google Script web app to automatically update data from a Google Sheet every 30 minutes. I initially attempted using the page refresh method, but encountered an issue where the web app would display a blank page upon refreshin ...