Pierpaolo Ercoli
Pierpaolo Ercoli

Reputation: 1064

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 (https://i.sstatic.net/PtZx6.jpg). I wanna rotate the black rectangle as per the screenshot in that url. Thanks in advance.

Upvotes: 0

Views: 824

Answers (1)

thedude
thedude

Reputation: 9812

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

Upvotes: 1

Related Questions