【问题标题】:how to use the svg matrix function to scale an svg back with the correct transform maths如何使用 svg 矩阵函数通过正确的变换数学来缩放 svg
【发布时间】:2018-10-14 11:35:16
【问题描述】:

如果你看下面的 sn-p,我想在 svg 图像上实现缩放。

我希望它能够优雅地放大和缩小。

我正在使用矩阵函数,我知道我可以通过更改第一个和第四个或矩阵或ad 来缩减。

我将以编程方式更改变换矩阵,但我希望将 svg 保持在中心,并且在放大和缩小时不让它向左上角或右下角移动。

矩阵的最后 2 个元素或 dxdy 的数学运算是什么,以使我的矩阵在缩放时保持居中?

<svg width="500" height="150">
<rect x="20" y="20" width="50" height="50" transform="matrix(.5,0,0,.5,0,0)" style="fill: #cc3333"></rect>
<rect x="20" y="20" width="50" height="50" transform="matrix(1,0,0,1,0,0)" style="fill: #cc3333"></rect>

<rect x="20" y="20" width="50" height="50" transform="matrix(1.5,0,0,1.5,0,0)" style="fill: #cc3333"></rect>

</svg>

【问题讨论】:

    标签: javascript svg


    【解决方案1】:

    这就是数学的运作方式。因为 SVG 的变换原点位于 SVG CANVAS 的原点(不是对象,与 CSS 不同) - 您首先必须平移形状,使其中心位于原点,然后缩放它,然后将中心移回它原来的位置。

    首先 - 一个小提示 - 要将 SVG 转换的 [a, b, c, d, e, f] 转换为“真实”的底层矩阵,您必须在矩阵 0 中添加第三行,0,1 换句话说,将 SVG 变换 [a, b, c, d, e ,f] 转换为实数矩阵,映射为:

    [ a  c  e ]
    [ b  d  f ]
    [ 0  0  1 ]
    

    所以 - 对于你的第一个形状 - 你的比例矩阵是这样的:

    [ 1.5  0  0 ]
    [  0  1.5 0 ]
    [  0   0  1 ]
    

    你翻译回原点矩阵(例如减 x,减宽度/2)是:

    [  1  0  -45 ]
    [  0  1  -45 ]
    [  0  0   1 ]
    

    将它们相乘(matrix multiplication 的便捷工具),你会得到这个中间矩阵:

    [  1.5  0  -45 ]
    [  0  1.5  -45 ]
    [  0    0   1  ]
    

    接下来,将该中间矩阵与您的“转换回原始位置矩阵”相乘,即:

    [  1  0   45 ]
    [  0  1   45 ]
    [  0  0   1  ]
    

    矩阵相乘的结果是:

    [  1.5  0 -22.5 ] 
    [  0  1.5 -22.5 ] 
    [  0    0   1   ]
    

    tada。

    <svg width="500" height="150">
    <rect x="20" y="20" width="50" height="50" transform="matrix(1.5,0,0,1.5,-22.5,-22.5)" fill="green"></rect>
    <rect x="20" y="20" width="50" height="50" transform="matrix(1,0,0,1,0,0)" fill="blue"></rect>
    <rect x="20" y="20" width="50" height="50" transform="matrix(.5,0,0,.5,22.5,22.5)" fill="red"></rect>
    
    
    
    
    </svg>

    【讨论】:

    • 当您声明并且您转换回原始矩阵(例如,负 x,负宽度/2)时,这个(负 x,负宽度/2)是从哪里来的:
    • 这是矩形中心与原点之间的距离。矩形的“x”属性是 20,矩形的宽度是 50 - 所以矩形的中心在 (20+50/2) = 45。所以要翻译回原点,它是 -45。
    【解决方案2】:

    你可以玩transform-origin。值由 给出: (rec.x + rect.width/2)px(rect.y + rect.height/2)px

    rect{
      transform-origin: 45px 45px;
    }
    <svg width="500" height="150">
    
    <rect x="20" y="20" width="50" height="50" transform="matrix(1.5,0,0,1.5,0,0)" style="fill: #003333"></rect>
    <rect x="20" y="20" width="50" height="50" transform="matrix(1,0,0,1,0,0)" style="fill: #cc3333"></rect>
    <rect x="20" y="20" width="50" height="50" transform="matrix(.5,0,0,.5,0,0)" style="fill: #0c3003"></rect>
    
    </svg>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-28
      • 2012-09-04
      • 2022-01-11
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      相关资源
      最近更新 更多