动画SVG视图框更改

Animate SVG viewBox change

本文关键字:视图 SVG 动画      更新时间:2023-09-26

我目前正在使用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解决方案

@伊恩给出了我最终使用的解决方案。结果是这样的:

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); 
        }
     });
}   

您可以通过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>

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

你没有理由不使用速度,但通过你自己的计算和进度/tweenValue参数,例如有点像这样的东西。。。

$("#mysvg").velocity(
    { tween: 200 },
    { progress: animViewbox }
)
function animViewbox (elements, complete, remaining, start, tweenValue) {
     elements[0].setAttribute('viewBox', '0 0 ' + tweenValue + ' ' + tweenValue);  
}

jsfiddle