KaoriYui
KaoriYui

Reputation: 912

Rotate svg in place using d3.js

I am trying to rotate a svg element with content using d3.js but it always gets out from the viewbox, what i want to achieve is rotate svg in place then later i can rotate the svg to 0,90,180,270deg but for now my goal is to rotate it in place.

My code is below ( i removed the irrelevant codes)

 var svgContainer = d3.select("body").append("svg")                                          
                    .attr("width",121)                                   
                    .attr("height", 108)
               //below is my code to rotate the svg
                attr('transform', 'rotate(180 0 0)')

My original svg

enter image description here

My output when putting attr('transform', 'rotate(180 0 0)')

enter image description here

What i want to achieve

enter image description here

My fiddle

https://jsfiddle.net/ewumar8d/4/

Upvotes: 1

Views: 7609

Answers (2)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You need to rotate the svg about its center and not 0,0.

So first you will need to add a group to the svg like this:

var svgContainer = d3.select("body").append("svg")
.attr("width", 121 + "mm")
.attr("height", 108 + "mm")
.attr('id','board') 
.style('background','#f4f4f4')
.style("border", "1px solid black").append("g");//add agroup

To this group add all your data points.

Next in order to rotate we need find the center about which we need to rotate.

            svgContainer.attr('transform',function(){
                var me = svgContainer.node()
                var x1 = me.getBBox().x + me.getBBox().width/2;//the center x about which you want to rotate
                var y1 = me.getBBox().y + me.getBBox().height/2;//the center y about which you want to rotate

                return `rotate(180, ${x1}, ${y1})`;//rotate 180 degrees about x and y
            }); 

working code here

Upvotes: 7

Alexey G
Alexey G

Reputation: 1118

try this:

   .attr('transform', 'rotate(180 0 0)')

Upvotes: 2

Related Questions