Table of Contents
Getting started with GSAP
完善动画
结论
参考文章
Home Web Front-end HTML Tutorial Quickly use svg to draw beautiful animations!

Quickly use svg to draw beautiful animations!

Feb 14, 2021 am 09:13 AM
css html javascript front end

Quickly use svg to draw beautiful animations!

I often see heroes using SVG to draw incredible animations on Codepen. I have always been curious about how they work. I always feel that this needs to be corrected. Only if you have a thorough understanding of SVG and draw those SVG patterns yourself can you make it move.

But that’s not the case. Today I will teach you a simple trick that will allow you to quickly implement an SVG animation!

Open Codepen, click the build button in the interface, you can use animation to build a house, and let it rise with smoke!

Demo address: https://codepen.io/johnYu243/pen/bGBVEwv

Quickly use svg to draw beautiful animations!

##Looking for exquisite svg patterns

Since we can’t draw it ourselves, we will look for ready-made libraries. There are many svg libraries. Websites such as Flaticon, iconfont, Iconfinder or icons8 will provide many free svg patterns.

Quickly use svg to draw beautiful animations!

Analyze svg pattern

Open

devtoolObserve the svg pattern, you will see the following The result:

Quickly use svg to draw beautiful animations!

elementpath and circle are both DOM elements of svg , respectively represent the lines and circles in the svg pattern.

For example:

<path></path>
Copy after login
The content of d in the above code: M represents moving the pen to (10, 25), then L draws a line to (10, 75), and finally Go back to the starting point and draw a triangle.

Through devtool, we can see which part of the pattern each

path corresponds to:

Quickly use svg to draw beautiful animations!

At this time, an idea should be formed, since We can know which part of the pattern each element corresponds to, and we can operate on the DOM elements we want to animate!

TimelineLite/TimelineMax Tool

If you use CSS or JavaScript to process animations by yourself simply through id and className, it is still quite difficult, and more importantly, it takes a lot of time

So we have to borrow tools. Timeline (Lite|Max) and TweenMax are well-known

GreenSock Animation Platform (GSAP for short) The createable timeline (timeline) launched by the well-known GreenSock Animation Platform (referred to as GSAP) is used as a container for animation or other timelines. This makes it easy to control the entire animation and precisely manage timing.

GSAP even provides us with Ease Visualizer to show the effect of each Ease function, and also attaches the code:

Quickly use svg to draw beautiful animations!

Demo address: https://codepen.io/johnYu243/pen/jOVbMzX

A few simple lines of code can achieve the following effects:

Quickly use svg to draw beautiful animations!

Getting started with GSAP

GSAP’s API function is very powerful, and there are related communities: Official website documentation, Forum, TimelineMax Chinese Manual

In the initial house construction example, I mainly used TimelineMax’s from and staggerFrom, which Both APIs only need to set initial values, and they will complete the tween animation within the specified time:

  tl.from("#House > rect:nth-child(24)", 1, {
      scaleX: 0,
      transformOrigin: "center",
      ease: Power2.easeOut
    })
Copy after login

In this step we will CSS Selector #House > rect:nth-child(24) This element starts from scaleX being 0, with center as the starting point for deformation, and uses Power2.easeOut to return to the original state within one second and perform compensation. animation.

    .staggerFrom(
      ["#House > path:nth-child(34)", "#House > path:nth-child(32)"],
      0.8,
      {
        scaleY: 0,
        transformOrigin: "bottom",
        ease: Bounce.easeOut,
        stagger: 0.2
      },
      0,
      "scene1+=0.5"
    )
Copy after login

is similar to from, except that staggerFrom can put multiple CSS Selectors at once, and use the stagger attribute to set the Selector in the array At what time difference will it appear?

For detailed API parameters, please refer to the Official Document

Then go back to our SVG, and with the help of devtool, we need to remove the CSS Selector# of the internal elements of the svg. ## It's very easy. Find the corresponding DOM element in the element panel, right-click, select Copy -> Copy selector, and you can directly copy it to the CSS Selector of the element:

Quickly use svg to draw beautiful animations!

现在我们能取得svg 中任意部分的CSS Selector,也知道怎么用GSAP API 来进行补间动画,现在是时候将其结合起来!

我们先调整下基本布局,一般在空白Html内直接放入svg时,图案大多会紧靠页面左上角,我们可以套用个margin: 0 auto将其置中,看起来会顺眼一些,你也能额外加些padding。我们在页面添加一个按钮来调用动画:

<!--html part-->
<button onclick="animateBike()"> Build! </button>
<!--css part-->
<style>
#Capa_1 {
  margin: 0 auto;
  display: block;
  width: 256px;
  height: 100%;
}
</style>
Copy after login

接着我们使用TimelineMax提供的staggerFrom函数,利用devtool将滑板车的轮子部分找出来,复制它们的CSS Selector,放入staggerFrom函数参数中,设定x与y轴的scale都从0开始,由center增长,采用Bounce.easeOut的ease function ,而四个Selector间以stagger: 0.2的属性值作为补间动画出现的时间差:

  const tl = new TimelineMax();
  tl.staggerFrom(
      [
        "#Capa_1 > g > path:nth-child(1)",
        "#Capa_1 > circle:nth-child(7)",
        "#Capa_1 > path:nth-child(6)",
        "#Capa_1 > circle:nth-child(5)"
      ],
      1,
      {
        scaleY: 0,
        scaleX: 0,
        transformOrigin: "center",
        ease: Bounce.easeOut,
        stagger: 0.2
      }
    )
Copy after login

简单几行代码,就能让我们的滑板车动起来!

演示地址:https://codepen.io/johnYu243/pen/poNjNzz

Quickly use svg to draw beautiful animations!

补间是一个术语,用于描述逐帧序列,有时也称为"中间"。 在那个地方,一个动作导致下一个动作产生一个流畅的动作。

完善动画

你可以把TimelineMax想像成时间轴,动画按指定顺序执行,而staggerFrom则可以同时让多个DOM元素以微小时间差的顺序启动,另外我们还可以设置一些Flag来指定要等到哪几个动画完成后,才接续其他动画。

最后,发挥自己的创意,使用各种API打出一套组合拳:

演示地址:https://codepen.io/johnYu243/pen/yLVYVey

Quickly use svg to draw beautiful animations!

结论

看到这里,跃跃欲试了吗?

总之,我自己觉得蛮有趣的,希望或多或少对读到这篇文章的人有点帮助。

最后给大家分享一个很酷的demo,来自我的文章封面

参考文章

GreenSock Animation Platform

How to Create Beautiful SVG Animations Easily

更多编程相关知识,请访问:编程教学!!

The above is the detailed content of Quickly use svg to draw beautiful animations!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

HTML: The Structure, CSS: The Style, JavaScript: The Behavior HTML: The Structure, CSS: The Style, JavaScript: The Behavior Apr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

Understanding React's Primary Function: The Frontend Perspective Understanding React's Primary Function: The Frontend Perspective Apr 18, 2025 am 12:15 AM

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of ​​componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.

The Future of HTML: Evolution and Trends in Web Design The Future of HTML: Evolution and Trends in Web Design Apr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML: Building the Structure of Web Pages HTML: Building the Structure of Web Pages Apr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

See all articles