簡體   English   中英

使用d3.js將svg旋轉到位

[英]Rotate svg in place using d3.js

我試圖使用d3.js旋轉帶有內容的svg元素,但它總是從視圖框中出來,我想要實現的是旋轉svg到位后來我可以將svg旋轉到0,90,180,270deg但是現在我的目標是將它旋轉到位。

我的代碼如下(我刪除了不相關的代碼)

 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)')

我原來的svg

在此輸入圖像描述

放入attr('transform', 'rotate(180 0 0)')時的輸出attr('transform', 'rotate(180 0 0)')

在此輸入圖像描述

我想要實現的目標

在此輸入圖像描述

我的小提琴

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

你需要圍繞它的中心旋轉svg而不是0,0。

首先,您需要將一個組添加到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

對此組添加所有數據點。

接下來為了旋轉,我們需要找到我們需要旋轉的中心。

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

這里工作代碼

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM