D3变换比例并保持位置不变

D3 transform the scale and keep the position unchanged

本文关键字:位置 变换 D3      更新时间:2023-09-26

我试图在d3中拖动一组元素,但当鼠标放在操作符上时,我也需要缩放组。

当我缩放组时,它会改变它的位置,当它在svg中的位置不变时,是否可以缩放它?

这是我工作的小提琴。

<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。

此处为工作代码。