使用d3.js在SVG中缩放矩形以适合文本

时间:2018-06-19 14:28:19

标签: javascript d3.js svg

如何使用d3.js在svg中缩放矩形以适合text

第一次运行yellowgreen rect可以很好地覆盖文本,但是如果您要调整屏幕大小,则文本大小和位置将被更改,而矩形保持不变。

下面是代码,这是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>

我希望矩形放大并随文本一起移动。有可能吗?

0 个答案:

没有答案