我试图在 d3 中拖动一组元素,但是当鼠标位于操作符上时,我还需要缩放该组。
当我缩放组时,它会改变其位置,是否可以在 svg 中的位置不变的情况下对其进行缩放?
这是fiddle我的工作。
<svg width="400" height="400" style="background-color: red">
<g id="op" class="operator">
<circle cx="50" cy="50" r="20" style="fill: yellow"></circle>
</g>
</svg>
script.js
d3.selectAll('.operator')
.on('mouseenter', function () {
console.log('Mouse Enter');
d3.select(this).attr('transform', 'scale(2)');
})
.on('mouseleave', function () {
console.log('Mouse Leave');
})
.call(d3.behavior.drag()
.on('drag', function () {
d3.select(this).attr('transform', 'translate(' + d3.event.x + ',' + d3.event.y + ')');
})
)
最佳答案
当你的比例为 2 时。
如果 cx 为 50,cy 为 50,则在比例 2 上,圆将出现在中心 cx * scale = 100 和 cy * scale=100 处。
这就是它规模跳跃的原因。现在,如果您希望圆位于同一位置,则需要执行以下操作:
d3.select(this).select("circle").attr("cx", 50/scale)
d3.select(this).select("circle").attr("cy", 50/scale)
除以比例,这将抵消圆心的比例效应。
因此缩放后新的 cx 和 cy 将为 25。
工作代码here .
关于javascript - D3 变换比例并保持位置不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34766841/