d3.js - D3 bounded dragging -


what have draggable line inside svg (about 300px). objective restrict how far line can move doesn't outside of svg. hour using d3 appreciated.

i've tried using if statements earlier none of them worked. here's code:

var svg = document.getelementbyid("probabilitydensitysvg"); var drag = d3.behavior.drag()     .on('dragstart', null)     .on('drag', function(d){ var dx = d3.event.dx; var dy = d3.event.dy; var x1new = parsefloat(d3.select(this).attr('x1'))+ dx; var y1new = parsefloat(d3.select(this).attr('y1')); var x2new = parsefloat(d3.select(this).attr('x2'))+ dx; var y2new = parsefloat(d3.select(this).attr('y2')); line.attr("x1",x1new)  .attr("y1",y1new)  .attr("x2",x2new)  .attr("y2",y2new); }).on('dragend', function(){ });   var line = d3.select(svg)   .append("line")   .attr("x1",100)   .attr("y1",143)   .attr("x2",100)   .attr("y2",370)   .attr("stroke-width",5)   .attr("stroke","black")   .call(drag); 

you can use nested ternary operator check boundaries.

for instance, limiting drag between 50 , 300 in x coordinate:

x1new = dx > 300 ? 300 : dx < 50 ? 50 : dx; 

here demo (i'm using d3.event.x instead of d3.event.dx):

var svg = d3.select("svg")  var drag = d3.behavior.drag()    .on('dragstart', null)    .on('drag', function(d) {      var dx = d3.event.x;      x1new = dx > 300 ? 300 : dx < 50 ? 50 : dx;      line.attr("x1", x1new)        .attr("x2", x1new);    }).on('dragend', function() {});    var line = svg.append("line")    .attr("x1", 100)    .attr("y1", 10)    .attr("x2", 100)    .attr("y2", 90)    .attr("stroke-width", 5)    .attr("stroke", "black")    .call(drag);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>  <svg width="350" height="100"></svg>


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -