简体   繁体   English

使用d3.js将svg旋转到位

[英]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. 我试图使用d3.js旋转带有内容的svg元素,但它总是从视图框中出来,我想要实现的是旋转svg到位后来我可以将svg旋转到0,90,180,270deg但是现在我的目标是将它旋转到位。

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 我原来的svg

在此输入图像描述

My output when putting attr('transform', 'rotate(180 0 0)') 放入attr('transform', 'rotate(180 0 0)')时的输出attr('transform', 'rotate(180 0 0)')

在此输入图像描述

What i want to achieve 我想要实现的目标

在此输入图像描述

My fiddle 我的小提琴

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

You need to rotate the svg about its center and not 0,0. 你需要围绕它的中心旋转svg而不是0,0。

So first you will need to add a group to the svg like this: 首先,您需要将一个组添加到svg,如下所示:

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 这里工作代码

尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM