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

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

Ansible warning on jinja2 braces on when -

html - How to custom Bootstrap grid height? -