简体   繁体   中英

Rotate a rectangle during drag D3

I am new on D3 v4 and D3 in general. I created a rectangle and I can drag it on the canvas. Now I want to dynamically rotate the rectangle basing on the circle's radius.

You can check my code here:

https://jsfiddle.net/n4m1r8nb/208/

I also tried to add rotate attribute on drag function, but if I add it, the rectangle move following the mouse as per x and y definition in the snippet you can see here below, without rotating, and an error appear ".rotate is not a function".

var drag = d3.drag().on("drag", function () {
                d3.select(this)
                    .rotate(d3.event.x)
                    .attr("x", d3.event.x)
                    .attr("y", d3.event.y);
                    console.log("X: ", d3.event.x)
                    console.log("Y: ", d3.event.y)
             })

You can see what I mean in this pic ( http://imgur.com/a/APbu9 ). I wanna rotate the black rectangle as per the screenshot in that url. Thanks in advance.

I have created a fiddle to demonstrate this: https://jsfiddle.net/hsspve49/

Relevant part of the code are in the drag handler:

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})`)
})

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