2017-09-01 128 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是大圓的半徑(拖動過程中)。