Reputation: 163
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})`);
Upvotes: 3
Views: 2322
Reputation: 102184
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>
Upvotes: 2