D3 SVG变换旋转过渡行为怪异 [英] D3 SVG transform rotation transition behaving weirdly

查看:22
本文介绍了D3 SVG变换旋转过渡行为怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 D3 生成了一个几何 SVG 图案,我想为它制作动画.我想让圆圈和正方形围绕它们的中心旋转.但是,当它们旋转时,中心点会沿椭圆路径移动,然后返回正确位置.

I generated a geometric SVG pattern with D3 and I wanted to animate it. I wanted to have the circles and square spinning around their centre. However when they rotate the centre point moves along an elliptical path before returning to the correct position.

我的代码笔在这里:http://codepen.io/andybarefoot/pen/bwkjaN单击左上角的旋转"会显示异常行为.我旋转组"的关键函数如下所示:

My codepen is here: http://codepen.io/andybarefoot/pen/bwkjaN Clicking "spin" in the top left corner shows the unusual behaviour. My key function for rotating the "group" looks like this:

    function spinCircles() {
        d3
            .select("#fixedGroup")
            .attr("transform", "translate (0, 0) rotate(0)")
            .transition()
            .duration(4000)
            .attr("transform", function(d, i){
                return "translate (0, 0) rotate (90,"+m/2+","+m/2+")";
            })
        ;
    }

我怀疑复杂性源于我将 SVG 元素与不同的视图框嵌套,因为我希望我的 SVG 具有响应性".(您可以调整窗口大小,对角线会改变角度以继续与屏幕的角对齐,而圆形和正方形保持相同的纵横比.)

I suspect the complexity arises from the fact that I have nested SVG elements with different viewboxes as I wanted my SVG to be "responsive". (You can resize the window and the diagonal lines will change angle to continue aligning with the corners of the screen, whilst the circles and square keep the same aspect ratio.)

嵌套 SVG 的代码如下所示:

The code for the nested SVGs looks like this:

        var baseSVG = d3.select("body")
            .append("svg")
            .attr("id", "baseSVG")
        ;
        var stretchSVG = baseSVG
            .append("svg")
            .attr("id", "stretchSVG")
            .attr("viewBox", "0 0 " + w + " " + h)
            .attr("preserveAspectRatio", "none")
        ;
        var fixedSVG = baseSVG
            .append("svg")
            .attr("id", "fixedSVG")
            .attr("viewBox", "0 0 " + m + " " + m)
        ;

但是,我也对我对 d3 中转移转换的糟糕理解持开放态度......

However I'm also open to the fault lying with my lousy understanding of transfer transitions in d3...

非常感谢您的任何帮助!

Any help very gratefully received!

推荐答案

要让 D3 围绕给定中心旋转,您需要提供自定义 tween 函数可以使用 字符串插值器:

For D3 to rotate around a given center, you need to provide a custom tween function which can make use of a string interpolator:

function spinCircles() {
  d3
    .selectAll("#fixedGroup")
    .transition()
    .duration(4000)
    .attrTween("transform", function() {
      var center = "" + m/2 + "," +  m/2;
      return d3.interpolateString("rotate(0," + center + ")", "rotate(90," + center + ")");
    });
} 

查看更新的 codepen 以获取工作示例.

Have a look at the updated codepen for a working example.

这篇关于D3 SVG变换旋转过渡行为怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆