2017-09-01 38 views
2

SVG中的元素如何不能被拖出SVG的范围? SVG的大小是固定的,可以拖动circle。你如何让内圈不能被拖出SVG边界?SVG中的元素如何不能被拖出SVG的范围?

地址:Demo online

这是最好的修改它的jsfiddle,谢谢!


源代码:

的Javascript:

var width = 300, height = 300; 
var color = d3.scale.category10(); 
var radius =16; 

var data = d3.range(20).map(function() { 
    return [ Math.random() * width/2, Math.random() * height/2 ]; 
}); 

var svg = d3.select("body").append("svg") 
    .attr("width", width) 
    .attr("height", height); 

var drag = d3.behavior.drag() 
    .origin(function(d) {return {x : d[0],y : d[1]};}) 
    .on("dragstart", function(){d3.select(this).attr("r",radius*2);}) 
    .on("drag", drag) 
    .on("dragend",function(){d3.select(this).attr("r",radius);}); 

var nodes=svg.selectAll("circle") 
    .data(data) 
    .enter() 
    .append("circle") 
    .attr("transform", function(d) {return "translate(" + 100 + "," + 100 + ")";}) 
    .attr("cx",function(d) { return d[0];}) 
    .attr("cy",function(d) { return d[1];}) 
    .attr("r",radius) 
    .attr("fill", function(d, i) { return color(i);}) 
    .call(drag); 

function drag(d) { 
    d[0] = d3.event.x; 
    d[1] = d3.event.y; 
    d3.select(this).attr("cx", d[0]).attr("cy", d[1]); 
} 

CSS:

svg { border:1px solid #d4d4d5} 

回答

2

在制动功能,只需约束的最大值和最小值为圆Cx和Cy基于SVG宽度/高度和圆半径的属性:

function drag(d) { 
    d[0] = Math.max(Math.min(d3.event.x,width-100-32),-100+32); 
    d[1] = Math.max(Math.min(d3.event.y,height-100-32),-100+32); 
    d3.select(this).attr("cx", d[0]).attr("cy", d[1]); 
} 

Here's an updated fiddle

-100是考虑到先前已应用了翻译。 32是大圆的半径(拖动过程中)。