【问题标题】:d3.js brush() inherits incorrect height and width From svg parent using viewBoxd3.js Brush() 使用 viewBox 从 svg 父级继承不正确的高度和宽度
【发布时间】:2018-10-24 16:02:24
【问题描述】:

我的根本问题是:有没有办法设置 d3 画笔窗口大小,以便在使用 viewBox 时像其他 SVG 组件一样从其父级正确继承?

详情: 我有两个链接的图表。第一个显示一组折线图,第二个是允许放大主图表的基本图表。它看起来几乎和这个例子一模一样:https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172

我想在图表中添加 svg 调整大小以允许我的图表自动调整。对于我的大多数图表,这很好用,但我的画笔窗口有问题。当我使用 SVG 视图框而不是显式使用父尺寸时,我的画笔区域被设置为整个 svg 的一个小区域(在我的情况下,画笔窗口是 300px x 150px 区域,而下面代码中的父 d3G 实际上是 1150 *100)。

下面是代码 sn-ps,用于以正常工作的方式初始化图表和画笔窗口:

  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('viewBox', '0 0 ' + this.parentNativeElement.offsetWidth + ' ' + this.parentNativeElement.offsetHeight)
.attr('preserveAspectRatio', 'none')
.attr('width', '100%')

我看过其他关于在 Firefox 上初始化范围的问题:https://github.com/d3/d3-brush/issues/13,但我没有设置范围,默认高度和宽度设置有错误。这也发生在 Chrome 上,而不是 firefox。

我对任何其他 svg 子集的默认高度和宽度设置没有任何问题,只有画笔窗口。

我还验证了我没有任何可以定义静态窗口大小的静态 css 设置。 Google devtools 显示该元素的高度和宽度也是自动/自动的。

【问题讨论】:

    标签: d3.js svg viewbox


    【解决方案1】:

    结果证明这是一个相当简单的修复。显然,画笔不接受默认(来自父级)设置来初始化高度和宽度。如果我设置一个,然后 100% 使用另一个,那么这足以让画笔正确初始化。以下是我最终用于配置调整大小的内容:

    .attr('width', '100%')
    .attr('height', this.parentNativeElement.offsetHeight)
    .attr('viewBox', '0 0 ' + this.parentNativeElement.offsetWidth + ' ' + this.parentNativeElement.offsetHeight)
    .attr('preserveAspectRatio', 'none')
    

    这会导致 svg 保持静态高度,并且仅在水平方向上缩放,但对画笔没有任何问题。

    【讨论】:

      猜你喜欢
      • 2015-03-25
      • 2020-08-22
      • 1970-01-01
      • 2017-05-26
      • 2014-12-03
      • 1970-01-01
      • 2012-05-16
      • 2019-12-06
      • 2018-08-07
      相关资源
      最近更新 更多