SVG viewBox变化时如何实现动画效果

4
我目前正在使用velocity.js来控制我创建的SVG图形上的一些动画。它与用户交互,因此当在某些部分发生点击时,图片可能向右或向下增长。到目前为止,一切都运作得很完美,直到图片变得太大而无法适应SVG框。在这种情况下,我只需要重新调整viewBox以缩放图像即可。
svgDoc.setAttribute("viewBox", "0 0 " + svgDocWidth + " " + svgDocHeight);

这个方案可行,但不够美观,因为它没有动画效果,只是直接跳转到新的尺寸。有没有办法使用velocity.js对视口框(viewBox)进行动画处理?
我已经尝试过以下方法:
$viewBox = $(svgDoc.viewBox);
$viewBox.velocity({height: svgDocHeight, width: svgDocWidth});

但是这样做并没有任何作用。

这是否超出了velocity.js的支持范围?

2015-11-21年的解决方案

@Ian给出了我最终使用的解决方案。 最终代码如下:

var origHeight = this.svgDoc.viewBox.animVal.height;
var origWidth = this.svgDoc.viewBox.animVal.width;

var docHeight = this.SvgHeight();
var docWidth = this.SvgWidth();

if ((origHeight != docHeight) || (origWidth != docWidth))
{
    var deltaHeight = docHeight - origHeight;
    var deltaWidth = docWidth - origWidth;

    $(this.svgDoc).velocity(
    { 
        tween: 1 
    },
    { 
        progress: function(elements, complete, remaining, start, tweenValue)
        {
            var newWidth = origWidth + complete * deltaWidth;
            var newHeight = origHeight + complete * deltaHeight;
            elements[0].setAttribute('viewBox', '0 0 ' + newWidth + ' ' + newHeight); 
        }
     });
}   
2个回答

9
您可以通过SMIL平滑地动画化viewBox。像这样...

<svg width="100%" height="100%" viewBox="0 0 200 200">
  <animate attributeName="viewBox" to="0 0 400 400" dur="5s" fill="freeze" />
  <circle cx="100" cy="100" r="100" fill="green" />
</svg>


0

我认为SMIL在Chrome中已被弃用(如果我错了,请纠正我),因此我猜想将会越来越依赖其他方法。

你完全可以使用velocity,但需要进行自己的计算,并使用progress/tweenValue参数,例如以下示例...

$("#mysvg").velocity(
    { tween: 200 },
    { progress: animViewbox }
)

function animViewbox (elements, complete, remaining, start, tweenValue) {
     elements[0].setAttribute('viewBox', '0 0 ' + tweenValue + ' ' + tweenValue);  
}

jsfiddle

的英译中为:

{{链接1:jsfiddle}}


如果Chrome移除了SMIL,那么有一些库/填充程序可以将其添加回来。 - Robert Longson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接