【问题标题】:svg.js strange interaction of scale and move/centersvg.js 比例和移动/中心的奇怪交互
【发布时间】:2014-03-18 13:48:34
【问题描述】:

我对在 js 中使用 svgs 不是很熟悉,但这绝对是一件奇怪的事情。 我有一个箭头,然后是一条应该将该箭头填充到一定程度的路径。看起来像这样: 现在我的目标是能够缩放白色部分,但它仍应保持在箭头 内。 现在奇怪的是,我无法弄清楚如何将白色部分移回正确的位置。我尝试过不同的尝试。 这是我当前的代码(它适用于 scaleFactor 1,但不适用于其他任何代码):

var draw = SVG('arrow').size(500, 500);
    var arrowPath=draw.polyline('10,243.495 202.918,15.482 397.199,245.107').fill('none').stroke({ width: 20 });

    var arrow=draw.group();
    arrow.add(arrowPath.clone());

    var scaleFactor=0.5;

    var fillArrow=draw.path('M357.669,198.387c-41.747,35.357-95.759,56.678-154.751,56.678c-58.991,0-113.003-21.32-154.75-56.676l154.75-182.907  L357.669,198.387z');
    fillArrow.fill('#ffffee');
    var moveX=(arrowPath.width()/2-fillArrow.width()/2)/scaleFactor+9.5;
    console.log(moveX);
    fillArrow.center(arrowPath.cx(), arrowPath.cy()).scale(scaleFactor);
//another attempt was
fillArrow.move(moveX,0);

【问题讨论】:

    标签: javascript svg svg.js


    【解决方案1】:

    当您在 SVG 中进行缩放、旋转和平移时,您就是在进行坐标变换。也就是说,你实际上并没有改变你正在绘制的对象,而是你正在绘制对象的坐标系。把它想象成像素在你的屏幕上有一定的大小,如果你这样做svgObject.scale(0.5),像素就会变成一半尺寸。

    因此,如果您通过path('M10,10 L20,10 L20,20 L10,20 z') 绘制一个正方形,然后应用scale(0.5),它看起来就像您绘制了一条看起来像path('M5,5 L10,5 L10,10 L5,10 Z') 的路径

    一开始这听起来可能很奇怪,但是当你能做到这一点时,很多几何计算就会变得简单得多。

    您想围绕箭头的尖端进行缩放(确保它不会移动)。然后您应该将该点放在 origo (0,0) 中并围绕该点绘制对象。在一个小组中这样做。因为这样您就可以将组坐标系转换到正确的位置。

    var draw = SVG('arrow').size(600, 600);
    
    // create a group
    var arrow = draw.group();
    
    // Draw the arrow path in the group
    // I have placed the "tip" of the arrow in (0,0)
    var arrowPath = arrow.polyline('-250,250 0,0 250,250').fill('none').stroke({
        width: 20
    });
    
    // Draw the fill arrow in the group. Again, the point 
    // I which to scale around is placed at (0,0)
    var fillArrow = arrow.path('M0,0L150,150,-150,150z').fill('#ffffee');
    
    // Move the group to the position we like to display it in the SVG
    arrow.move(260, 20);
    
    var scaleFactor = 0.5
    fillArrow.scale(scaleFactor);
    

    这是一个工作示例,您可以在其中测试和更改比例因子。 http://jsfiddle.net/ZmGQk/1/

    这里很好地解释了平移、旋转和缩放的工作原理。 http://commons.oreilly.com/wiki/index.php/SVG_Essentials/Transforming_the_Coordinate_System

    【讨论】:

    • 谢谢!我发现在我的情况下,不使用比例函数更容易,而只需将宽度+高度乘以比例因子。这样它实际上也是线性缩放的。这就是我需要的。
    猜你喜欢
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多