转换过渡

时间:2014-11-25 17:57:57

标签: javascript svg d3.js

如前面的问题所述(例如d3.js Odd Rotation Behavior),如果要在其位置旋转SVG对象,则应使用

.attr('transform','rotate(45,100,100)')

其中第一个数字是旋转度数,另外两个是旋转原点的坐标。

这里的问题是我想在转换中执行旋转:

.transition()
.attr('transform', 'rotate(45,100,100)')
.duration(300)

我得到一个奇怪的行为,我可以在预期的轮换之前看到翻译。 您可以在此处查看结果:http://jsfiddle.net/uwM8u/121/

有没有更好的方法来获得这个?

2 个答案:

答案 0 :(得分:3)

D3的方法是使用custom tween function,在这种情况下是一个简单的字符串插值:

.attrTween("transform", function() {
  return d3.interpolateString(d3.select(this).attr("transform"),
      "rotate(" + (rotation+=45) + "," +
        (diamond.x+diamond.width/2) + "," +
        (diamond.y+diamond.width/2) + ")");
})

完整演示here

答案 1 :(得分:1)

使用翻译添加父<g>元素,这样您实际上是围绕原点旋转形状。

var svg = d3.select("body")
            .append("svg")
            .attr("width", 400)
            .attr("height", 300);
        svg         
            .append("text")
            .text("click the square")
            .attr("x", w/2)
            .attr("y", w/2)
        svg
            .append("g")
            .attr("transform", "translate(" + diamond.x + "," + diamond.y +")")
            .append("rect")
            .attr("transform", "rotate(" + rotation + ")")
            .attr("x", -diamond.width / 2)
            .attr("y", -diamond.width / 2)
            .attr("height", diamond.width)
            .attr("width", diamond.width)
            .attr("fill", "teal")
            .on("mousedown", function(){
              d3.select(this)
                  .transition()
                  .attr("transform", "rotate("+ (rotation+=45) +")")
                 .duration(300)           
            });

jsfiddle

相关问题