Javascript 我可以使用d3.js中的drag.container来限制拖动区域吗?

Javascript 我可以使用d3.js中的drag.container来限制拖动区域吗?,javascript,d3.js,Javascript,D3.js,我试图理解d3.drag(),但我无法掌握本节的内容,因此我在这里寻求帮助 我的理解是这样的:如果我添加容器函数,那么我可以限制可以拖动的区域。如果解释正确,那么我如何使用它 例如,在下面的代码片段中,我创建了一个可以拖动的圆。但我只想把拖动区域限制在白色圆圈内。我可以使用drag.container()来执行此操作吗 文件 const svg=d3.select(“body”).append(“svg”).attr(“width”、“600”).attr(“height”、“500”).s

我试图理解d3.drag(),但我无法掌握本节的内容,因此我在这里寻求帮助

我的理解是这样的:如果我添加容器函数,那么我可以限制可以拖动的区域。如果解释正确,那么我如何使用它

例如,在下面的代码片段中,我创建了一个可以拖动的圆。但我只想把拖动区域限制在白色圆圈内。我可以使用drag.container()来执行此操作吗


文件
const svg=d3.select(“body”).append(“svg”).attr(“width”、“600”).attr(“height”、“500”).style(“background”、“lightblue”);
//我可以用这个圆圈作为容器吗?
const circleAsContainer=svg.append(“circle”).attr(“cx”,“180”).attr(“cy”,“200”).attr(“r”,“120”).attr(“fill”,“white”)
const circle=svg.append(“circle”).attr(“cx”,“120”).attr(“cy”,“150”).attr(“r”,“30”).attr(“fill”,“orange”).call(d3.drag)()
.on(“开始”,“事件,d)=>圆圈.attr(“笔划”,“黑色”).attr(“笔划宽度”,“4”))
.on(“拖动”(event,d)=>circle.attr(“cx”,d=>event.x).attr(“cy”,d=>event.y))
.on(“结束”,“事件,d)=>圆圈.attr(“笔划”,“无”))
);

容器元素仅确定event.x和event.y坐标的坐标系。例如,如果使用一些SVG元素支持的“dx”和“dy”属性相对于另一个元素定位可拖动圆,那么这将非常有用。但是,container()不会自动约束event.x和event.y以适应给定元素的可视边界

详细说明Ouroborus的评论:拖动事件处理程序中有以下行:

circle.attr("cx", d => event.x).attr("cy", d => event.y))
在函数“d=>event.x”和“d=>event.y”中,必须根据与您所称的“容器”形状相对应的数学公式约束event.x和event.y

例如,要将可拖动图元约束在矩形区域内,公式很简单:

 circle.attr('cx', d => {
    if (event.x > 60 + 240) { // El dragged beyond the right-hand border
      return 60 + 240
    } else if (event.x < 60) { // El dragged beyond the left-hand border
      return 60
    } else {  // El is within the box's horizontal bounds
      return event.x
    }
  })
circle.attr('cx',d=>{
如果(event.x>60+240){//El拖到右侧边界之外
返回60+240
}else如果(event.x<60){//El拖到左侧边界之外
返回60
}else{//El在框的水平边界内
返回事件.x
}
})
对于y轴,边界公式如下所示。 最终结果如下所示(运行代码段并尝试):


文件
const svg=d3.select('body')。append('svg')。attr('width','600')。attr('height','500')。style('background','lightblue'))
const containingRect=svg.append('rect')
.attr('x','60')
.attr('y','80')
.attr('width','240')
.attr('height','240')
.attr('填充','灰色')
//我可以用这个圆圈作为容器吗?
const circleAsContainer=svg.append('circle').attr('cx','180').attr('cy','200').attr('r','120').attr('fill','white'))
const circle=svg.append('circle').attr('cx','120').attr('cy','150').attr('r','30').attr('fill','orange'))
.call(d3.drag()
.on('start',(event,d)=>circle.attr('stroke','black')。attr('stroke-width','4'))
.on('拖动',(事件,d)=>
circle.attr('cx',d=>{
如果(event.x>60+240){//El拖到右侧边界之外
返回60+240
}else如果(event.x<60){//El拖到左侧边界之外
返回60
}else{//El在框的水平边界内
返回事件.x
}
}).attr('cy',d=>{
如果(event.y>80+240){//El被拖出顶部边界
返回80+240
}如果(event.y<80){//El被拖出底部边界,则为else
返回80
}否则{//El在长方体的垂直边界内
返回事件
}
})
).on('end',(event,d)=>circle.attr('stroke','none'))
)

对不起,我该怎么做?这就是我可以约束拖动区域的方法-非常感谢!