javascript - 如何使用视图框在 D3 中使 SVG 响应?
问题描述
我注意到在各种示例中,SVG 是响应式的(根据窗口大小的变化而改变大小),有时在使用 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
.
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);
推荐阅读
- android - 在 Fragment 页面底部截断项目
- c++ - QStringList.size 返回两个值
- javascript - NetSuite:TypeError:log.debug 不是客户端脚本中的函数(SuiteScript 2.0)
- dask - Distributed.scheduler.KilledWorker 异常的根本原因是什么?
- ios - 带有约束的 Swift UITextView 不可见
- symfony-4.3 - 路由 symfony4 中的 NotFoundHttpException
- android - 使用合并标签时复合视图不可见
- ruby - 查找具有相同数字的下一个最小数字
- google-kubernetes-engine - GKE 上的 HAProxy 入口控制器
- c# - 在元组列表中查找具有最高 Item1 值的元组 - 然后将其从列表中删除