我正在尝试在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 *刻度= 100和cy *刻度= 100的中心。

这就是为什么它会大规模发展的原因。现在,如果您希望圆在同一位置,则需要执行以下操作:

d3.select(this).select("circle").attr("cx", 50/scale)
d3.select(this).select("circle").attr("cy", 50/scale)


除以比例,这将抵消圆心的缩放效果。

因此,后缩放后新的cx和cy将为25。

工作代码here

09-25 17:14
查看更多