简体   繁体   English

拖动事件D3时旋转矩形

[英]Rotate a rectangle on dragging event D3

Hi everybody I am trying to rotate a rectangle while the user drag it with mouse. 大家好,我正在尝试旋转一个矩形,同时用户用鼠标拖动它。 The rectangle follow a circular curve. 矩形遵循圆形曲线。 Below I attach my solution that is perfect, but the mouse is always on top left corner of the rectangle. 下面我附上我的解决方案,它是完美的,但是鼠标始终位于矩形的左上角。 I want that the mouse would be always in the center of the rectangle during dragging. 我希望鼠标在拖动过程中始终位于矩形的中心。 How can I control it ? 我该如何控制?

Solution: 解:

var drag = d3.drag().on("drag", function () {
            var rect = d3.select(this);
            var theta = Math.atan2(d3.event.y - height/2, d3.event.x - width/2) * 180 / Math.PI


            rect
                .attr("x", d3.event.x)
                .attr("y", d3.event.y)
                .attr('transform', `rotate(${theta + 90}, ${d3.event.x}, ${d3.event.y})`)



         })

Full code of my solution you can see here: https://jsfiddle.net/hsspve49/ 您可以在这里查看我的解决方案的完整代码: https : //jsfiddle.net/hsspve49/

Offset the x and y attribute in the drag handler by the size of your rectangle, eg: 将拖动处理程序中的x和y属性偏移矩形的大小,例如:

...
.attr("x", d3.event.x - 15) // half the width
.attr("y", d3.event.y - 35) // half the height
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM