【问题标题】:Scale SVG element to given area using Snap animations使用 Snap 动画将 SVG 元素缩放到给定区域
【发布时间】:2016-07-22 09:43:56
【问题描述】:

我想缩放 SVG 元素的动画以适应(保持纵横比)SVG 的给定区域。

我知道执行相对动画的动画

var s = Snap("#myelement"); s.animate({ '变换' : 't100,100s5,5,165,175' },1000);

原则上应该可以通过计算平移和缩放的参数来实现我想要的。 那里的问题是我找不到参数的准确文档。 t 的参数似乎是相对 x,y 位置,s 的参数是比例因子和比例中心的坐标。 但是,组合的平移和缩放如何工作?相对平移位置是否随着缩放等而缩放?

换句话说:如何从动画目标元素的左上角和右下角坐标计算相对平移和缩放参数?

或者:Snap中是否有更合适的动画功能?

【问题讨论】:

    标签: javascript animation svg


    【解决方案1】:

    由于Snap 使用 SVG 语法,要解决这个问题需要了解 SVG 转换(请参阅此处了解介绍:https://sarasoueidan.com/blog/svg-transformations/)。为了设置组合 SVG 变换,重要的是要了解每个变换都会改变坐标系(而不仅仅是绝对坐标系中元素的属性)。

    如果你结合两个变换,缩放和平移,这意味着第二个变换的参数取决于第一个。

    要在SVG的ViewBox坐标中将元素平移和缩放到给定位置和大小,可以首先执行缩放到新大小,选择中心坐标作为缩放中心的元素。那么以下翻译的考虑简化如下

    function startAnimation() {
    
    var svg = Snap("#baseSVG");
    /* get the bounding box of the svg */
    var bboxSvg = svg.getBBox();
    
    var s = Snap("#element");
    /* get the bounding box of the element */
    var bbox = s.getBBox();
    /* get the required scale factor (assuming that we want to fit the element inside the svg bounding box) */
    var scale = Math.min(bboxSvg.width/bbox.width,bboxSvg.height/bbox.height)*0.8;
    /* compute the translation needed to bring center of element to center of svg 
    the scale factor must be taken into account since the translation is based on the coordinate system obtained after the previous scaling */
    var tx = (200-bbox.cx)/scale;
    var ty = (200-bbox.cy)/scale;
    /* perform the animation (make center of scaling the center of element) */
    s.animate({ 'transform' : 's' + scale + ',' + scale + ',' + bbox.cx + ',' + bbox.cy + 't' + tx + ',' + ty },1000,mina.bounce);
    s.drag();
    } 
    

    这假设您的 SVG 对象的 id 为 baseSVG,而您要转换的元素的 id 为 element。它经过转换以适合 SVG(如果您希望它更大或更小,请调整因子 0.8)。如果您只知道元素角的坐标,则必须首先计算目标的中心坐标(替换 bbox.cxbbox.cy)和比例以应用此代码 sn-p。这在baseSVG 的坐标系中以明显的方式起作用。

    【讨论】:

      【解决方案2】:

      你展示了一个包含几个部分的变换。这些部分的顺序很重要。如果您先平移后缩放,则生成的平移也会缩放。如果您先缩放然后平移,则生成的平移不受缩放影响。

      您在 Snap.svg 中使用的动画是我也使用的动画。 (但是我考虑迁移到 svg.js,因为 Snap.svg 不能很好地与 Electron 配合使用。不过,我必须先做一些测试)

      【讨论】:

        猜你喜欢
        • 2015-04-23
        • 2016-08-20
        • 1970-01-01
        • 1970-01-01
        • 2015-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多