简体   繁体   中英

How do I draw text in a rectangle in D3?

I am using this calendar example: http://bl.ocks.org/KathyZ/c2d4694c953419e0509b and I want to put the value that appears in the mouseover inside each cell so it's always visible. I've tried adding this, which I thought would print '!!!' in each cell but it doesn't:

rect.append("text")
attr("dx", "+.65em")
.attr("dy", "+.65em")
.attr("opacity", "1")
.text(function(d) { return '!!!'; });

but it doesn't do anything

As I said in my comments, you want to group your rect and text in a g element. Here's the simplest example:

 <!DOCTYPE html> <html> <head> <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script> </head> <body> <script> var data = [{ x: 20, y: 30, text: "Hi" }, { x: 100, y: 200, text: "bye" }]; var svg = d3.select("body") .append("svg") .attr("width", 500) .attr("height", 500); var g = svg.selectAll('.someClass') .data(data) .enter() .append("g") .attr("class","someClass") .attr("transform", function(d) { return "translate(" + dx + "," + dy + ")"; }); g.append("rect") .attr("width", 40) .attr("height", 40) .style("fill", "red"); g.append("text") .style("fill", "black") .text(function(d) { return d.text; }) </script> </body> </html> 


For the specific code you are looking at .day becomes a g :

var g = svg.selectAll(".day")
    .data(function(d) { 
      return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1));
    })
    .enter().append("g")
    .attr("class", "day")
    .attr("transform", function(d){
       var month_padding = 1.2 * cellSize*7 * ((month(d)-1) % (no_months_in_a_row));
       var x = day(d) * cellSize + month_padding; 
       var week_diff = week(d) - week(new Date(year(d), month(d)-1, 1) );
       var row_level = Math.ceil(month(d) / (no_months_in_a_row));
       var y = (week_diff*cellSize) + row_level*cellSize*8 - cellSize/2 - shift_up;
       return "translate(" + x + "," + y + ")";
    });

var rect = g.append("rect"))
    .attr("width", cellSize)
    .attr("height", cellSize)
    .datum(format);

 g.append("text") 
   .text("!!!")
   .style("fill", "black"); 
   // etc, etc, etc....

the text attribute doesn't mean anything for a rect object. you want to add a separate text element: .enter().append("svg:text") and then .text(function(d) { return '!!!' }); and you can style the text element accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM