我有一个 SVG 组,里面有一个矩形,我希望矩形充当组的边框...
<g>
<rect></rect>
</g>
但组是动态的,其内容会发生变化。我正在尝试在我的更新函数中调整矩形的大小
.attr("x", function(d) { return this.parentNode.getBBox().x })
.attr("y", function(d) { return this.parentNode.getBBox().y })
.attr("width", function(d) { return this.parentNode.getBBox().width })
.attr("height", function(d) { return this.parentNode.getBBox().height })
但似乎发生的情况是它扩展得相对较好,但随后无法正确收缩,因为组的边界框宽度现在与展开后的矩形宽度相同(矩形的宽度是组的宽度,但组的宽度现在是矩形的宽度)。
有没有办法让 SVG 组内的矩形正确调整大小并充当边框?
最佳答案
解决这个问题的方法不止一种。
使用
outline
属性(2014-08-05 状态:适用于 Chrome 和 Opera)<svg xmlns="http://www.w3.org/2000/svg" width="500px" height="500px"> <g style="outline: thick solid black; outline-offset: 10px;"> <circle cx="50" cy="60" r="20" fill="yellow"/> <rect x="80" y="80" width="200" height="100" fill="blue"/> </g> </svg>
参见 live example .
使用
filter
生成边框(2014-08-05 状态: 在 Firefox 中有效,但 Chrome/Opera 在 feMorphology 上有一个 bug ,但应该可以通过使用其他过滤器原语来解决这个问题。<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"> <defs> <filter id="border" x="-5%" y="-5%" width="110%" height="110%"> <feFlood flood-color="black" result="outer"/> <feMorphology operator="erode" radius="2" in="outer" result="inner"/> <feComposite in="inner" in2="outer" operator="xor"/> <feComposite in2="SourceGraphic"/> </filter> </defs> <g filter="url(#border)"> <circle cx="50" cy="60" r="20" fill="yellow"/> <rect x="80" y="80" width="200" height="100" fill="blue"/> </g> </svg>
参见 live example .
以上两者都会自动更新到组的任何大小,无需修改 DOM。
关于javascript - D3 - 围绕 SVG 组创建动态 "Border"矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25086712/