简体   繁体   中英

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/

Offset the x and y attribute in the drag handler by the size of your rectangle, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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