简体   繁体   English

如何为 SVG 多边形点设置动画?

[英]How to animate SVG polygon points?

I have created a line chart with SVG (polygon points) that I would like animated.我用我想要动画的 SVG(多边形点)创建了一个折线图。

I would like the points to all start animating from the X axis, and when finished animating, the result to look like the following image.我希望所有点都从 X 轴开始动画,动画完成后,结果如下图所示。

It seems there is no simple way to achieve this, with the googling I have done.通过我所做的谷歌搜索,似乎没有简单的方法可以实现这一目标。 Any tips would be most appreciated, thanks.任何提示将不胜感激,谢谢。

在此处输入图片说明

What do you mean by "animating from the X axis" exactly? “从 X 轴制作动画”究竟是什么意思? Do you mean start flat and grow upwards to this shape?你的意思是开始平坦并向上生长到这个形状?

If so, it is actually very easy.如果是这样,那其实很容易。

 <svg viewBox="0 0 2040 352"> <defs> </defs> <polygon points="" fill="red"> <animate attributeName="points" dur="1s" fill="freeze" from="0,352, 550,352, 1240,352, 1592,352, 1880,352, 2040,352, 2040,352,0,352" to="0,292, 550,232, 1240,258, 1592,158, 1880,168, 2040,0, 2040,352,0,352"/> </polygon> </svg>

This example uses vanilla SVG SMIL animations.此示例使用 vanilla SVG SMIL 动画。 You can also use one of a number of SVG graphing or animation libraries.您还可以使用许多 SVG 图形或动画库之一。

This effect can be easily achieved with transform:scaley keyframe animation:使用transform:scaley关键帧动画可以轻松实现此效果:

(javascript code in followind snippet is only for generating random svg polygon) (followind 片段中的 javascript 代码仅用于生成随机 svg 多边形)

 let n = 5, w = innerWidth - 20, h = innerHeight - 20; let pts = Array(n).fill(0).map((_, i) => [(1+i)*(w/(n+1)), -Math.random()* h]); document.body.innerHTML += `<svg width=${w} height=${h} viewbox=0,${-h},${w},${h} > <polygon points=0,0,${pts},${w},0 /></svg>`;
 @keyframes grow { 0% {transform: scaley(0)} 100% {transform: scaley(1)} } polygon { fill: #e45; animation: grow 0.5s forwards; }

I have done something in the past, this was however with a single control point of a SVG Bezier curve.我过去做过一些事情,但是这是使用 SVG Bezier 曲线的单个控制点。 However I think you can apply the same principle.但是我认为您可以应用相同的原则。 I think you need to do the following steps我认为您需要执行以下步骤

  1. Create an array with y values of the curves使用曲线的 y 值创建一个数组
  2. Create a jQuery animate function with a step method for each y value [jquery animate 1为每个 y 值创建一个带有 step 方法的 jQuery 动画函数 [jquery animate 1

animate example动画示例

$({ n: 0 }).animate({ n: 40}, {
        duration: 1000,
        step: function(calculatedYValue, fx) {
            //update graphs with calculatedYValue
            console.log(parseInt(calculatedYValue), 10);   
        }
    });    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM