How to draw text in a rectangle in d3?

Member

by rollin , in category: Javascript , 9 months ago

How to draw text in a rectangle in d3?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 9 months ago

@rollin 

To draw text in a rectangle in D3, you can use the following steps:

  1. Create a rectangle using the D3 rect element. You can specify the x, y, width, and height attributes to define the position and size of the rectangle.
1
2
3
4
5
6
svg.append("rect")
    .attr("x", 50)
    .attr("y", 50)
    .attr("width", 200)
    .attr("height", 100)
    .attr("fill", "lightgrey");


  1. Add text inside the rectangle using the D3 text element. You can specify the x, y, and text attributes to define the position and text content of the text element.
1
2
3
4
5
svg.append("text")
    .attr("x", 100)
    .attr("y", 100)
    .text("Hello, D3!")
    .attr("fill", "black");


  1. Optionally, you can also style the text using CSS properties like font-family, font-size, text-anchor, and alignment-baseline.
1
2
3
4
5
6
7
8
9
svg.append("text")
    .attr("x", 100)
    .attr("y", 100)
    .text("Hello, D3!")
    .attr("fill", "black")
    .style("font-family", "Arial")
    .style("font-size", "16px")
    .style("text-anchor", "middle")
    .style("alignment-baseline", "middle");


By following these steps, you can draw text inside a rectangle in D3 and customize its appearance as needed.