简体   繁体   中英

d3: when a line move to specific positions call function

I move a vertical line in horizontal direction, and I want to implement this:

when the line move to specific position ,for example, x1 = 100, and this will trigger a movement calling function(x1)

Is this possible?

Here is my horizontal transition code:

<html>
<head>
  <script src="d3.min.js"></script>
</head>

<body>

  <div class="control-buttons">
    <button class="pause">
      Pause
    </button>
    <button class="continue">
      Continue
    </button>    
  </div>
  <svg width="1000" height="500">
    <line x1="100" y1="0" x2="100" y2="100" stroke="black"/>
  </svg>
</body>

<script>   
  d3.select('button.pause').on('click', function() {
    d3.select("line").interrupt();
  });

  d3.select('button.continue').on('click', function() {
  d3.select("line").transition()
    .ease(d3.easeLinear)
    .duration(10000)
    .attr("x1",800)
    .attr("x2",800);
  }).dispatch('click');
</script>
</html>

I have thought about a way, set small time interval and check the status over and over again, but this method is obviously not good. There should be a way that defines what to do when triggers something, something like define 'x1=100' as a event?

Don't know how to do or search. Any help is appreciated.

I think you can use the tween call to interpolate the position over the transition. In this example, the console log interpolates values between 0 and 800 over the transition. You can set your behavior using that - here I change the color of the line to red:

d3.select("line").transition()
    .ease(d3.easeLinear)
    .duration(10000)
    .attr("x1",800)
    .attr("x2",800)
    .tween('position', function() {
        var interpol = d3.interpolate(0,800);
      return function(t){
        var val = interpol(t);
        if(val > 100) { d3.select('line').style('stroke', 'red')}
        console.log(val);
      }
    });

https://jsfiddle.net/m8Lt93qc/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM