我的根本问题是:有没有办法设置d3画笔窗口大小,以便在使用viewBox时可以像其他SVG组件一样正确地继承它?
详细说明: 我有两个链接的图表。第一个显示一组折线图,第二个是允许缩放主图表的基本图表。它看起来几乎与此示例完全相同:https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172
我想在图表中添加svg resizing以允许我的图表自动调整。对于我的大多数图表,这很好用,但我的画笔窗口有问题。当我使用SVG视图而不是显式使用父级大小时,我的画笔区域被设置为整个svg的一个小区域(在我的情况下,画笔窗口是300px x 150px区域,而下面代码中的父d3G实际上是1150) * 100)。
以下是以正确方式初始化图表和画笔窗口的代码片段:
this.width = this.parentNativeElement.offsetWidth - this.margin.left - this.margin.right;
this.height = this.parentNativeElement.offsetHeight - this.margin.top - this.margin.bottom;
this.d3G = this.d3.select(this.parentNativeElement).append('svg')
//change in the next two attr lines
.attr('width', this.parentNativeElement.offsetWidth)
.attr('height', this.parentNativeElement.offsetHeight)
.append<SVGElement>('g')
.attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');
// ... some other initialization here (scale, domain, line drawing functions etc)
this.d3G.append('g')
.attr('class', 'brush')
.call(this.d3.brushX().on('end', () => this.brushed() )
对于我的所有图表,我需要做的唯一真正的改变是更改“宽度”和“高度”attr线并将其替换为:
.attr('viewBox', '0 0 ' + this.parentNativeElement.offsetWidth + ' ' + this.parentNativeElement.offsetHeight)
.attr('preserveAspectRatio', 'none')
.attr('width', '100%')
我看过其他关于在Firefox上初始化Extents的问题的帖子:https://github.com/d3/d3-brush/issues/13,但我没有设置范围,我在默认的高度和宽度设置方面有错误。这也发生在Chrome上,而不是Firefox。
我对任何其他svg子集的默认高度和宽度设置没有任何问题,只有刷子窗口。
我还验证了我没有任何静态css设置可以定义静态窗口大小。 Google devtools也显示该元素的高度和宽度是自动/自动的。
答案 0 :(得分:0)
事实证明这有一个相当简单的修复。显然,画笔不接受默认(从父级)设置来初始化高度和宽度。如果我设置一个,然后使用100%的另一个,那么这是刷子正确初始化的足够信息。这是我用于配置调整大小的最终内容:
.attr('width', '100%')
.attr('height', this.parentNativeElement.offsetHeight)
.attr('viewBox', '0 0 ' + this.parentNativeElement.offsetWidth + ' ' + this.parentNativeElement.offsetHeight)
.attr('preserveAspectRatio', 'none')
这会导致svg保持静态高度,并且仅在水平方向上缩放,但刷子没有任何问题。