SVG 中的元素怎么不能拖出 SVG 的范围?



如何无法将SVG中的元素拖出SVG的范围?SVG的大小是固定的,可以拖动circle。如何使内部圆无法从SVG边界中拖出?

地址:在线演示

最好在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}

在阻力函数中,只需根据SVG宽度/高度和圆形半径来约束圆CX和CY属性的最大值和最小值:

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]);
}

这是一个更新的小提琴

-100将考虑以前应用的翻译。32是大圆的半径(在拖动期间)。

最新更新