【问题标题】:How to .move() a selected brush?如何 .move() 选定的画笔?
【发布时间】:2018-08-10 01:30:37
【问题描述】:

TL;DR:你如何移动d3.select('#a_brush')

问题

我在<g> 群组中有画笔,名为axes。每个<g> 轴包含一个d3 轴和一个d3 画笔。在axes 的更新选择中,我想更新 d3 轴和画笔。

axes.each(function (d) { d3.select(this).select('.axis').call(d3.axisBottom(d[1])) });
axes.each(function (d) { d3.select(this).select('.brush').call(brush.move, f(d)) });

在上面,axes 是一个更新选择。假设f(d) 产生一个合适的数组。两行中的第一行有效,但第二行抛出:

Uncaught TypeError: Cannot read property 'move' of undefined

这可能是因为我在任何地方都没有保存名为画笔的变量。我希望直接在选择上调用.move 方法,而不必保存画笔变量

在选择中移动画笔的合适命名是什么

axes.each(function (d) { d3.select(this).select('.brush') ?? ... somehow move the brush to f(d) ...

注意事项

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    您绝对应该为您的画笔定义一个变量(或常量),例如:

    const brush = d3.brush();
    

    这样,您无需每次都自定义范围和其他参数。但是,如果出于某种原因您真的不想这样做,只需将 brush 更改为 d3.brush()

    d3.select(this).select('.brush').call(d3.brush().move, f(d))
    

    这是一个基本的演示,点击按钮移动画笔:

    const svg = d3.select("svg");
    
    const g = svg.append("g");
    
    g.call(d3.brush());
    
    d3.select("button").on("click", function() {
      g.call(d3.brush().move, [
        [100, 0],
        [400, 100]
      ])
    })
    svg {
      background-color: wheat;
    }
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <button>Click</button>
    <br>
    <svg width="500" height="100"></svg>

    【讨论】:

    • 我不将画笔保存到变量的原因是因为我有很多画笔,在输入选择中定义:.each(function (d) { d3.select(this).call(d3.brushX().extent(...).on("start", brushstart).on("brush", brush).on("end", brushend) ) })。我应该制作一个刷子数组或对象来抓住它们吗?
    • 是的,你应该这样做。
    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多