如何使用 viewbox 在 D3 中使 SVG 响应?
How to make SVG responsive in D3 with viewbox?
我注意到在各种示例中,SVG 是响应式的(根据 window 尺寸的变化而改变尺寸),有时在使用 viewbox / preserveAspectRatio 时它没有响应。
这是一个非常简单的例子。我像其他所有示例一样在 SVG 元素上使用 viewbox 和 preseverAspectiRatio,但是它没有响应,为什么?
<html>
<meta charset="utf-8">
<body>
<div id ="chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script>
var svgContainer = d3.select("#chart")
.append("svg")
.attr("width", 200)
.attr("height", 200)
.attr("viewBox", "0 0 100 100")
.attr("preserveAspectRatio", "xMinYMin meet")
//Draw the Circle
var circle = svgContainer.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 50);
</script>
</body>
</html>
目前您的 svg 没有调整大小,因为您已经为 200x200
的 svg 容器指定了一个固定的 with。
var svgContainer = d3.select("#chart")
.append("svg")
.attr("width", 200) // setting fixed width
.attr("height", 200) // setting fixed width
一个解决方案是将这些更改为百分比,这将重新缩放到其父项的大小。
var svgContainer = d3.select("#chart")
.append("svg")
.attr("width", '100%') // percent width
.attr("height", 100%) // percent height
另一种可能的解决方案是使用 Window#resize
事件,并根据变化更改 svg 的大小。
window.addEventListener('resize', function () {
// select svg and resize accordingly
});
我应该在 chrome 中补充一点,您可以使用 ResizeObserver 来观察 svg 父级大小的变化,并相应地调整 svg 的大小。
const resizeOb = new ResizeObserver((entries: any[]) => {
for (const entry of entries) {
const cr = entry.contentRect;
const width = cr.width; // parent width
const height = cr.height; // parent height
// resize svg
}
});
this.resizeOb.observe(svgParentElement);
我注意到在各种示例中,SVG 是响应式的(根据 window 尺寸的变化而改变尺寸),有时在使用 viewbox / preserveAspectRatio 时它没有响应。 这是一个非常简单的例子。我像其他所有示例一样在 SVG 元素上使用 viewbox 和 preseverAspectiRatio,但是它没有响应,为什么?
<html>
<meta charset="utf-8">
<body>
<div id ="chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script>
var svgContainer = d3.select("#chart")
.append("svg")
.attr("width", 200)
.attr("height", 200)
.attr("viewBox", "0 0 100 100")
.attr("preserveAspectRatio", "xMinYMin meet")
//Draw the Circle
var circle = svgContainer.append("circle")
.attr("cx", 50)
.attr("cy", 50)
.attr("r", 50);
</script>
</body>
</html>
目前您的 svg 没有调整大小,因为您已经为 200x200
的 svg 容器指定了一个固定的 with。
var svgContainer = d3.select("#chart")
.append("svg")
.attr("width", 200) // setting fixed width
.attr("height", 200) // setting fixed width
一个解决方案是将这些更改为百分比,这将重新缩放到其父项的大小。
var svgContainer = d3.select("#chart")
.append("svg")
.attr("width", '100%') // percent width
.attr("height", 100%) // percent height
另一种可能的解决方案是使用 Window#resize
事件,并根据变化更改 svg 的大小。
window.addEventListener('resize', function () {
// select svg and resize accordingly
});
我应该在 chrome 中补充一点,您可以使用 ResizeObserver 来观察 svg 父级大小的变化,并相应地调整 svg 的大小。
const resizeOb = new ResizeObserver((entries: any[]) => {
for (const entry of entries) {
const cr = entry.contentRect;
const width = cr.width; // parent width
const height = cr.height; // parent height
// resize svg
}
});
this.resizeOb.observe(svgParentElement);