簡體   English   中英

D3 wordcloud為每個術語/單詞添加背景顏色

[英]D3 wordcloud add background color for each term/word

我想用此特定術語/單詞的背景框突出顯示用戶單擊的每個術語/單詞。 我使用點擊功能,可以訪問和設置單詞本身的顏色,但無法設置單詞的背景。 我該如何實現?

這是我的繪畫功能:

function draw(words) {
  d3.select("#interests").append("svg")
    .attr("width", w)
    .attr("height", h)
  .append("g")
    .attr("transform", "translate(" + [w >> 1, h >> 1] + ")")
  .selectAll("text")
    .data(words)
  .enter().append("text")
    .style("font-size", function(d) { return d.size + "px"; })
    .style("font-family", "Impact")
    .style("fill", function(d, i) { return fill(i); })
    .style("cursor", "pointer")
    .attr("text-anchor", "middle")
    .attr("transform", function(d) {
      return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
    })
    .text(function(d) { return d.text; })
    .on("click", function(d) {
        // d3.select(this).style("fill");
        d3.select(this).style("background","yellow");
        if (d.inGraph == true){
            d.inGraph = false;
            unloadInterest(d.text);
        } else {
            d.inGraph = true;
            loadInterest(d.text, "#ff0000");
        }

     });
}

text元素沒有背景樣式或屬性。 要突出顯示單詞,您必須創建一個與文本大小相同的rect元素(尺寸為getBBox() )。

您的代碼可以如下修改。

function draw(words) {
      var main_g = d3.select("#interests").append("svg")
        .attr("width", w)
        .attr("height", h)
      .append("g")
        .attr("transform", "translate(" + [w >> 1, h >> 1] + ")")

      main_g.selectAll("text")
        .data(words)
      .enter().append("text")
        .style("font-size", function(d) { return d.size + "px"; })
        .style("font-family", "Impact")
        .style("fill", function(d, i) { return fill(i); })
        .style("cursor", "pointer")
        .attr("text-anchor", "middle")
        .attr("transform", function(d) {
          return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
        })
        .text(function(d) { return d.text; })
        .on("click", function(d) {
            var bbox = this.getBBox();
            main_g.insert("rect",":first-child")
              .attr("x", bbox.x)
              .attr("y", bbox.y)
              .attr("width", bbox.width)
              .attr("height", bbox.height)
              .style("fill", "yellow");


            if (d.inGraph == true){
                d.inGraph = false;
                unloadInterest(d.text);
            } else {
                d.inGraph = true;
                loadInterest(d.text, "#ff0000");
            }

         });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM