【问题标题】:Make a SVG transform matrix rotate around its center使 SVG 变换矩阵围绕其中心旋转
【发布时间】:2012-12-01 20:18:32
【问题描述】:

HTML

<rect id="red" style="fill: red;" height="100" width="20"></rect>

JS

var layer = 
{  
    sizeReal   : { "width": 20, "height": 100 }                   
,   sizeScaled : { "width": 10, "height": 50 }
,   position   : { "x": 200, "y": 200 } 

,   scale      : 0.5
,   rotation   : 0
,   matrix     : [ 1, 0, 0, 1, 0, 0 ]
};

// Not sure if its the cleanest way but it works it rotates itself arounds its center.
//
$("#red")[0].setAttribute( 'transform', 'translate(' + layer.position.x + ',' + layer.position.y +') rotate(' + layer.rotation +',' + ( layer.sizeScaled.width  / 2 ) + ',' + ( layer.sizeScaled.height / 2 ) + ') scale(' + layer.scale + ',' + layer.scale +')' ) 

现在我只想对矩阵做同样的事情。我正在使用 sylvester 来乘以矩阵。

我做了一个小提琴来澄清问题:)

http://jsfiddle.net/xYsHZ/3/

我希望红色矩形的行为与绿色矩形相同。我做错了什么?

【问题讨论】:

    标签: javascript math matrix svg transform


    【解决方案1】:

    已修复!!矩阵元素的顺序是错误的:)

    $("#red")[0].setAttribute( 'transform', 'matrix(' + layer.matrix[ 0 ][ 0 ] + ',' + layer.matrix[ 1 ][ 0 ] + ',' + layer.matrix[ 0 ][ 1 ] + ',' + layer.matrix[ 1 ][ 1 ] + ',' + layer.matrix[ 0 ][ 2 ] + ',' + layer.matrix[ 1 ][ 2 ] + ')' );
    },50);
    

    http://jsfiddle.net/6DR3D/2/

    【讨论】:

      【解决方案2】:

      问题在于rotate(angle, x, y) 调用。 此调用围绕点 (x,y) 以给定角度旋转。 但是,您构建矩阵以围绕 layer.position 旋转。

      为了围绕给定点 (x,y) 旋转,相对于对象,您需要先平移到 (-x,-y),然后旋转,然后再平移回 (x,y)。

      所以如果你有一个矩阵乘法函数 Mul,它可能看起来像这样:

      var m1 = GetMatrix(0, 0, {"x":-layer.sizeScaled.width/2, "y":-layer.sizeScaled.height/2});
      var m2 = GetMatrix(layer.rotation, layer.scale, layer.position);
      var m3 = GetMatrix(0, 0, {"x":layer.sizeScaled.width/2, "y":layer.sizeScaled.height/2});
      
      var m = Mul(Mul(m3,m2), m1); //i.e. apply the matricdes in order m1, then m2, then m3
      

      【讨论】:

      • 所以我基本上会将 3 个矩阵应用于 svg 元素。还是 mul() 将 3 合并为 1?
      • mul 将三者合二为一——它只是矩阵的乘法
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多