gpt4 book ai didi

javascript - viewbox SVG 属性导致图形间隔很远

转载 作者:太空宇宙 更新时间:2023-11-04 13:08:52 25 4
gpt4 key购买 nike

我在 cordova/phonegap 页面上有多个 D3 图表,我想让它们缩放以适应水平/垂直屏幕。只要我注释掉早期的宽度和高度属性,添加“Viewbox”和“presereAspectRatio”的属性就可以做到这一点。

图表在页面上定义为:

   <div id="graph1"></div>
<div id="graph2"></div>
<div id="graph3"></div>
etc....

并且可以很好地处理“宽度”和“高度”的静态属性

但是当我添加“viewbox”属性时,它们的缩放比例非常好,但现在彼此之间的间距约为 15 厘米,导致您必须长时间向下滚动手机才能看到它们。

如果我注释掉“viewbox”和“preserveAspectRatio”并取消注释原始静态“width”和“height”属性,图形将像以前一样一个接一个地出现在屏幕上。但它们是静态的。我不确定每个内部或外部的哪个方面会受此影响。

下面是我用于选择方面等的代码。

    var margin = {
top: 40,
right: 20,
bottom: 35,
left: 40
},
width = 475 - margin.left - margin.right,
height = 205 - margin.top - margin.bottom;



var svg = d3.select("#graph1")
.append("svg")
.attr("viewBox","0 0 475 205")
.attr("preserveAspectRatio", "xMinYMin")

// .attr("width", width + margin.left + margin.right)
// .attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

对此有任何想法将不胜感激。

谢谢;)

最佳答案

当你离开 widthheight ,它们被设置为 100%,这意味着高度将是视口(viewport)的 100%。这意味着额外的空间会添加到 svg 的底部。您可以通过创建 <rect> 来测试它这是您的 viewBox 的大小,并在 svg 元素上放置一个边框。

HERE是一个例子。如您所见,作为 svg 元素一部分的 viewBox 之外(未被矩形覆盖)有额外的空间。

不幸的是,您可能需要使用脚本来调整 svg 的大小。您可以创建一个函数来根据容器的宽度(在您的情况下可能是 body 元素)以及 viewBox 中的高度和宽度的比率来设置 height 属性。这是一种方法:

function resizeAll() {
d3.selectAll('svg').call(scaleSvg);
}

function scaleSvg(sel) {
sel.each(function() {
// split the viewbox into its component parts
var vbArray = d3.select(this).attr('viewBox').split(' ');
// find the ratio of height to width
var heightWidthRatio = +vbArray[3] / +vbArray[2];
// get the width of the body (or you could use some other container)
var w = document.body.offsetWidth;
// set the width and height of the element
d3.select(this)
.attr('width', w)
.attr('height', w * heightWidthRatio);
});
}

然后您只需调用 resizeAll()页面加载时以及窗口调整大小时。

HERE是一个例子。

关于javascript - viewbox SVG 属性导致图形间隔很远,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24844355/

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