How to rotate an object around the center in d3.js

后端 未结 2 1717
你的背包
你的背包 2020-12-15 11:46

I have two simple objects in d3.js, they should be circling around the center of the viewport (like planets around the sun).

I am new to d3.js and I know that I have

2条回答
  •  眼角桃花
    2020-12-15 12:41

    I know this might come too late. But I do hope this can help future readers if they also are facing the same problem. I created fiddles and add some explanation in here, hope it can help:

    http://www.zestyrock.com/data-visualization/d3-rotate-object-around-the-center-object-part-2/

    Here is the code:

    var start = Date.now();
    
    var mode = 0;
    
    var svg = d3.select("#canvas")
        .append("svg")
        .attr("width", 500)
        .attr("height", 500);
    
    svg.append("circle")
        .attr("r", 50)
        .attr("cx", 250)
        .attr("cy", 250)
        .attr("fill", "#e05038");
    
    var rotateElements = svg.append("g");
    
    rotateElements.append("circle")
        .attr("r", 25)
        .attr("cx", 250)
        .attr("cy", 50)
        .attr("fill", "#f2b632")
        .attr("class", "orangeNode");
    
    rotateElements.append("line")
        .attr("x1", 250)
        .attr("y1", 75)
        .attr("x2", 250)
        .attr("y2", 200)
        .attr("class", "edge")
        .attr("stroke", "grey");
    
    
    d3.select("#start")
        .on("click", startAnimation);
    
    function startAnimation() {
        if (mode === 0) {
            d3.timer(function() {
                var angle = (Date.now() - start);
                var transform = function() {
                    return "rotate(" + angle + ", 250, 250)";
                };
                d3.selectAll(".orangeNode, .edge")
                    .attr("transform", transform);
    
                if (mode === 0) {
                    return true;
                } else {
                    return false;
                }
            });
            mode = 1;
        } else {
            mode = 0;
        }
    
    }
    

提交回复
热议问题