gpt4 book ai didi

javascript - 中心 SVG 组元素

转载 作者:行者123 更新时间:2023-11-30 14:07:47 24 4
gpt4 key购买 nike

我正在尝试使用 d3 在 svg 元素中将具有 textg 元素与 tspan 居中 使用下面的代码。

var rootSVGSize = d3.select("svg.root-svg").node().getBoundingClientRect()
var dataLabelSize = d3.select("g.data-label").node().getBoundingClientRect()

var x = rootSVGSize.width / 2;
var y = rootSVGSize.height / 2;

d3.select("g.data-label").attr("transform", "translate(" + x + "," + y + ")")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<svg class="root-svg" width="180" height="200" style="border: black;border-style: solid;border-width: 1px;">
<g class="data-label">
<text alignment-baseline="middle" style="font-family: Arial; font-size: 36px; font-style: normal; font-weight: normal; fill: rgb(242, 200, 15);" text-anchor="middle">
<tspan x="0" dy="0">1/1/2018</tspan>
<tspan x="0" dy="41">3:00:00</tspan>
<tspan x="0" dy="41">AM</tspan>
</text>
<title>1/1/2018 3:00:00 AM</title>
</g>
</svg>

如您在执行上述代码后所见,组元素未正确居中于 x 和 y 坐标。如何在 svg 中使组元素居中?

我正在使用 getBoundingClientRect 因为我想在分配 widthheight 后在初始阶段获取 svg 的大小> 那是在 svg 中呈现任何内容之前。

最佳答案

您必须考虑 SVG 容器和组的 xy 位置:

var x = (rootSVGSize.x - dataLabelSize.x) + (rootSVGSize.width - dataLabelSize.width) / 2;
var y = (rootSVGSize.y - dataLabelSize.y) + (rootSVGSize.height - dataLabelSize.height) / 2;

这样,您可以为 alignment-baselinedominant-baselinetext-anchor 设置任何值,它不会没关系,该组将始终居中。

这里是你的代码有那个变化:

var rootSVGSize = d3.select("svg.root-svg").node().getBoundingClientRect()
var dataLabelSize = d3.select("g.data-label").node().getBoundingClientRect()

var x = (rootSVGSize.x - dataLabelSize.x) + (rootSVGSize.width - dataLabelSize.width) / 2;
var y = (rootSVGSize.y - dataLabelSize.y) + (rootSVGSize.height - dataLabelSize.height) / 2;

d3.select("g.data-label").attr("transform", "translate(" + x + "," + y + ")")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<svg class="root-svg" width="180" height="200" style="border: black;border-style: solid;border-width: 1px;">
<g class="data-label">
<text alignment-baseline="middle" style="font-family: Arial; font-size: 36px; font-style: normal; font-weight: normal; fill: rgb(242, 200, 15);" text-anchor="middle">
<tspan x="0" dy="0">1/1/2018</tspan>
<tspan x="0" dy="41">3:00:00</tspan>
<tspan x="0" dy="41">AM</tspan>
</text>
<title>1/1/2018 3:00:00 AM</title>
</g>
</svg>

关于javascript - 中心 SVG 组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55084902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com