1

How could I scale a rectangle in svg to fit the text using d3.js.

When you run it for the first time the yellowgreen rect covers the text nicely, but if you will resize the screen the text size and position will be changed, while the rectangle stays the same.

Below is the code, here is the fiddle:

    debugger;
var svg = d3.select("#drawRegion")
  .append("svg")
  .attr("width", "100%")
  .attr("height", "100%");
svg.append("rect")
  .attr("x", "0")
  .attr("y", "0")
  .attr("width", "100%")
  .attr("height", "100%")
  .attr("fill", "yellow");

const rectAroundText = svg
  .append("rect");

const textMiddleX = 50;
const textMiddleY = 50;

const testText = svg
  .append("text");
testText
  .attr("x", textMiddleX + "%")
  .attr("y", textMiddleY + "50%")
  .attr("text-anchor", "middle")
  .attr("alignment-baseline", "central")
  .attr("x", "50%")
  .attr("y", "50%")
  .attr("fill", "#000")
  .classed("scalingText", true)
  .text("svdfv");
  
  const textBox = testText.node().getBBox();
  
  rectAroundText
 .attr("x", textBox.x)
  .attr("y", textBox.y)
  .attr("width", textBox.width)
  .attr("height", textBox.height)
  .attr("fill", "yellowgreen");
    <div id="drawRegion">

</div>
<script src="https://d3js.org/d3.v5.min.js"></script>

I would like the rectangle to scale up and move along with the text. Is it possible?

oobarbazanoo
  • 397
  • 1
  • 5
  • 15

0 Answers0