Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate objects in D3.js

I'm trying to rotate rectangles according to some data. With, the following code, the rotation applies to the whole line. How can I get each "rect" to have his own rotation applied, keeping them on the same line?

let canevas = d3.select("body")
    .append("svg")
    .attr("width", 1000)
    .attr("height", 1000);

let rectangles = d3.select("svg")
    .selectAll("rect")
    .data([10, 20, 30, 40])
    .enter()
    .append("rect")
    .attr("x", (d, i) => (i * 30) + 30)
    .attr("y", 20)
    .attr("width", 20)
    .attr("height", 20)
    .attr("transform", (d) => `rotate(${d})`);
like image 635
Le Sparte Avatar asked Dec 11 '25 02:12

Le Sparte


1 Answers

That's the normal behaviour of rotate, since the rotate function of the translate attribute rotates the elements around the origin of the coordinates system (0,0).

An easy solution is setting the positions in the same translate:

let canevas = d3.select("body")
   .append("svg")
   .attr("width",300)
   .attr("height",100);

let rectangles = d3.select("svg")
   .selectAll("rect")
   .data([10,20,30,40])
   .enter()
   .append("rect")
   .attr("width",20)
   .attr("height",20)
   .attr("transform", (d,i) => `translate(${(i*30)+30},30) rotate(${d})`);
<script src="https://d3js.org/d3.v4.min.js"></script>
like image 179
Gerardo Furtado Avatar answered Dec 13 '25 15:12

Gerardo Furtado