jasondavies / d3-cloud

Create word clouds in JavaScript.
https://www.jasondavies.com/wordcloud/
Other
3.82k stars 1.08k forks source link

Layout not obeying size inside d3 selectAll loop. #162

Closed vsanka14 closed 1 year ago

vsanka14 commented 4 years ago

I have several rectangles and I am trying to create a wordcloud "inside" each rectangle. To achieve this I am obtaining the bounding box of each rectangle. From the bounding box, I am getting the height and width of the rectangle and passing it to the layout size() function. However it looks like the layout isn't obeying the size being passed. Can anyone please tell me what I'm doing wrong?

Information about the DOM elements in my code:

  1. Each rectangle resides inside a g element. I have assigned the class 'wordG' to all of these g elements.
  2. The aim is to have a wordcloud layout inside each of these g elements.

Below is my code snippet which isn't working as expected:

d3.selectAll('.wordG')
.each(function(d){
    let gId = d3.select(this).node().id;
    let rect = d3.select(this).select('rect');
    let rectBox = rect.node().getBBox();
    let dWords = d.data.words;

    var layout = d3.layout.cloud()
        .size([rectBox.width, rectBox.height])
        .words(dWords.map(function(d1) { return {text: d1.word, size:d1.size}; }))
        .padding(2)   
        .rotate(function() { return ~~(Math.random() * 2) * 1; })
        .fontSize(function(d1) {return d1.size; })      
        .text(function(d1) { return d1.text; }) 
        .on("end", draw);

    function draw(words) {
        let parentSvg = d3.select(`#${gId}`);
        parentSvg
        .append("g")
        .attr("transform", "translate(" + rectBox.x + "," + rectBox.y +  ")")
        .selectAll("text")
        .data(words)
        .enter().append("text")
            .attr('class', 'wordcloud')
            .style("font-size", function(d1) { return d1.size; })
            .style("fill", "#69b3a2")
            .attr("text-anchor", "middle")
            .style("font-family", "Impact")
            .attr("transform", function(d1) {
                return "translate(" + [d1.x, d1.y] + ")";
            })
            .text(function(d1) { return d1.text; });
    }

    layout.start();
});