gpt4 book ai didi

javascript - 组元素的 SVG getBBox() 给出与具有相同大小和位置的矩形元素不同的结果

转载 作者:行者123 更新时间:2023-11-30 11:51:46 25 4
gpt4 key购买 nike

我在组元素和矩形元素上执行 getBBox()。 group 元素和 rect 元素具有相同的位置和大小。 getBBox() 组始终将 x,y 设为 0,0,而 rect 给出其在外部组中的实际位置。为什么会这样? group 元素的 getBBox() 是否应该像 rect 元素那样仅返回其父元素内的边界?以下 html 将以下内容打印到控制台:

SVGRect { x: 0, y: 0, width: 800, height: 400}<br/>
SVGRect { x: 0, y: 0, width: 100, height: 100}<br/>
SVGRect { x: 100, y: 200, width: 100, height: 100}<br/>

var superg = d3.select("#canvasHolder").append("svg").attr("width", 800).attr("height", 400)
.append("g").attr("id", "superg")

superg.append("rect").attr("width", 800).attr("height", 400).style("fill", "blue").style("fill-opacity", 0.2)
superg.append("rect").attr("width", 100).attr("height", 100).style("fill", "red").style("fill-opacity", 0.2).attr("id", "rect").attr("x", 100).attr("y", 200)

superg.append("g").attr("transform", "translate(100, 200)").attr("id", "g")
.append("rect").attr("cx", 0).attr("cy", 0).attr("width", 100).attr("height", 100)

console.log(d3.select("#superg").node().getBBox())
console.log(d3.select("#g").node().getBBox())
console.log(d3.select("#rect").node().getBBox())
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="canvasHolder"></div>

我原以为组元素应该具有与矩形元素相同的 x 和 y 值。为什么不是这样?

最佳答案

我们需要查看生成的 SVG 才能找到答案。我将专注于内部 <g id="g">并去除其余部分。

<g transform="translate(100, 200)" id="g">
<rect cx="0" cy="0" width="100" height="100"></rect>
</g>

通过调用 getBBox() 返回的边界矩形值在一个元素上 不包括任何 transform 的影响 该元素的属性。它仅根据其子项的边界框计算。

参见:the definition of getBBox() in the SVG 1.1 spec

所以调用getBBox()在组上仅包括其 <rect> 的尺寸 child ,因此 (0, 0, 100, 100)。但是 <rect> 受其父级提供的转换的影响,因此当您获得它的 bbox 时,您将获得 (100, 200, 100, 100)。

关于javascript - 组元素的 SVG getBBox() 给出与具有相同大小和位置的矩形元素不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39237210/

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