Table of Contents
Basics and common misunderstandings of SMIL animation
values ​​Pairing usage with keyTimes attribute
SVGSVGElement level animation control
Accurate control of single SMIL animations
ElementTimeControl interface and its methods
Example: Control specific animations through buttons
Optimize SMIL animation structure
Merge alternating animations
The function of fill="freeze"
Complete sample code
Home Web Front-end HTML Tutorial Precise control and optimization practice of SVG SMIL animation

Precise control and optimization practice of SVG SMIL animation

Aug 23, 2025 pm 06:18 PM

Precise control and optimization practice of SVG SMIL animation

This tutorial explores in detail how to precisely control SMIL animations in SVG, especially pause and play for specific elements. The article corrects common misunderstandings, such as the global animation control of SVGSVGElement, and introduces the fine management of single animations through the beginElement() and endElement() methods of the ElementTimeControl interface. At the same time, the tutorial also provides best practices to optimize animation structure, simplify alternating animations, and ensure consistency in animation behavior.

Basics and common misunderstandings of SMIL animation

In SVG, SMIL (Synchronized Multimedia Integration Language) provides a declarative way to define animations. However, in practical applications, developers often encounter some misunderstandings about animation control.

values ​​Pairing usage with keyTimes attribute

When using the element for animation, if the values ​​attribute is specified to define the sequence of keyframe values ​​of the animation, a corresponding keyTimes attribute must be provided at the same time. The keyTimes property defines the time point in which each value in the values ​​list occurs, the value should be a semicolon-separated sequence of incremental numbers between 0 and 1, and the number must be the same as the number of values ​​in the values.

For example, if values="value1;value2", then keyTimes must be "0;1". If values="value1;value2;value3", then keyTimes can be "0;0.5;1". If keyTimes are omitted, or their value does not match values, the animation may not be played or controlled properly.

Error example (keyTimes missing) :

 <animate attributename="d" values="pathData1;pathData2" dur="1.5s"></animate>

Correct example (add keyTimes) :

 <animate attributename="d" values="pathData1;pathData2" keytimes="0;1" dur="1.5s"></animate>

SVGSVGElement level animation control

SVG DOM provides the SVGSVGElement interface, which contains pauseAnimations() and unpauseAnimations() methods. The purpose of these methods is to pause or restore all SMIL animations inside the entire SVG element . This means that if you call these methods on an SVG root element with multiple animations, all animations will be paused or resumed at the same time.

For example, the following code will pause or restore all animations within the SVG element with ID svg:

 document.getElementById("svg").pauseAnimations(); // Pause all animations document.getElementById("svg").unpauseAnimations(); // Restore all animations

This global control method cannot meet the need to control only specific animations. For example, in an SVG, part of the animation needs to be continuously run, while the other part requires user interaction to control.

Accurate control of single SMIL animations

To achieve precise control of a single SMIL animation in SVG, we need to utilize the methods provided by the ElementTimeControl interface, which can be called directly on the element.

ElementTimeControl interface and its methods

The ElementTimeControl interface provides the following key methods to control the playback of a single animation:

  • beginElement(): Start the animation. If the animation is already active, calling this method will start it again.
  • endElement(): End the animation. Calling this method will immediately stop the animation and return it to its initial state (unless fill="freeze" is set).

It should be noted that beginElement() and endElement() provide the start and end control of the animation, but they do not provide the function of "pause" in the intermediate state like the video player. To achieve a pause-like effect, it is often necessary to combine other techniques, or redesign the animation logic.

Example: Control specific animations through buttons

Suppose we have an SVG that contains two sets of animations: the animation of the poi_back group needs to be continuously running, while the animation of the poi_front group needs to be controlled by buttons to control its start and stop.

First, make sure your element has a unique id so that it can get its reference via JavaScript. For animations that require manual control, set its begin property to "indefinite", indicating that it will not start automatically and needs to be triggered manually through beginElement().

HTML structure :

 <button id="startButton">START</button>
<button id="stopButton">STOP</button>
<svg width="100%" height="100%" version="1.1" viewbox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" id="svg">
    <!-- ... Omit the bottle path... -->

    <!-- Rear animation (continuously running) -->
    <path fill="#9bc300" id="poi_back">
        <animate id="poi_back_animation" attributename="d" values="m 62.692,157.03 c ... initial state...; m 62.692,157.03 c ... intermediate state...; m 62.692,157.03 c ... initial state..." keytimes="0;0.5;1" begin="0s" automatic start-->
            dur="3s"
            repeatCount="indefinite"
        />
    </animate></path>    

    <!-- Front animation (manual control) -->
    <g id="poi_front">
        <path fill="#739a00">
            <animate id="poi_front_animation" attributename="d" values="m62.692 157.03c ... Initial state...; m 62.692,157.03c ... Intermediate state...; m62.692 157.03c ... Initial state..." keytimes="0;0.5;1" begin="indefinite" manual control-->
                dur="3s"
                repeatCount="indefinite"
                fill="freeze" <!-- Keep the final state after the animation is over->
            />      
        </path> 
    </g>    
</svg>

JavaScript control logic :

 // Get the animation element that needs to be controlled const poiFrontAnimation = document.getElementById("poi_front_animation");

// Add event listener document.getElementById("startButton").onclick = function() {
    poiFrontAnimation.beginElement(); // Start poi_front animation};   

document.getElementById("stopButton").onclick = function() {
    poiFrontAnimation.endElement(); // Stop poi_front animation};

CSS style (keep the same, for page layout) :

 html, body {
    height: 100%;
    margin: 0%;
    padding: 0%;
    overflow: hidden;
}
body {
    height: 100vh;
    display: flex;
    background-color: #2a0000;
    box-sizing: border-box;
    flex-direction: column;
    align-items: center;
}  
#startButton {
    width: 60px;
    height: 30px; 
    background-color: orange;
    position: relative;
    margin-top: 5px;
    margin-bottom: 5px;
}
#stopButton {
    width: 60px;
    height: 30px; 
    background-color: yellow; 
    position: relative;
    margin-top: 5px;
    margin-bottom: 5px;
}

In this example, the beginning="0s" of poi_back_animation makes it automatically start and loop infinitely after the page is loaded. The begin="indefinite" of poi_front_animation makes it wait for the user to click the "START" button to start through the beginElement() method, and click the "STOP" button to stop through the endElement() method.

Optimize SMIL animation structure

Original SMIL animations often implement alternating animations through chain triggering (for example, begin="0s;poi_back_2.end"). This approach, while feasible, adds complexity in management and debugging, especially when manual control is required, the trigger of endEvent may accidentally restart the painting.

Merge alternating animations

A simpler practice is to merge two alternating animations into a element. This can be achieved by extending the values ​​and keyTimes properties.

For example, if the animation alternates between state A and state B, we can define values="StateA;StateB;StateA" and set keyTimes="0;0.5;1". In this way, the animation will go from A to B and then back to A in dur time, completing a complete loop.

Structure before optimization (two alternating animations) :

 <animate id="anim_1" attributeName="d" values="StateA;StateB" begin="0s;anim_2.end" dur="1.5s"/>
<animate id="anim_2" attributeName="d" values="StateB;StateA" begin="anim_1.end" dur="1.5s"/>

Optimized structure (a merge animation) :

 <animate 
    id="single_anim"
    attributeName="d"
    values="StateA;StateB;StateA"
    keyTimes="0;0.5;1"
    dur="3s" <!-- Duplicate duration->
    repeatCount="indefinite"
    begin="0s" <!-- or "indefinite" -->
/></animate></path></g></svg>

In this way, the animation logic becomes clearer and easier to control through beginElement() and endElement(), because there is only one animation element that needs to be managed.

The function of fill="freeze"

When the animation ends, the element's properties will usually return to the state before the animation begins. If you want the element to remain in its final state after the animation is over, you can set the fill="freeze" attribute on the element. This is very useful when you stop an animation and want it to stay at the last frame of the animation.

Complete sample code

Below is a complete example code combining all the optimization and control strategies mentioned above.




    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVG SMIL animation precision control</title>
    <style>
        html, body {
            height: 100%;
            margin: 0%;
            padding: 0%;
            overflow: hidden;
        }
        body {
            height: 100vh;
            display: flex;
            background-color: #2a0000;
            box-sizing: border-box;
            flex-direction: column;
            align-items: center;
        }  
        #startButton {
            width: 60px;
            height: 30px; 
            background-color: orange;
            position: relative;
            margin-top: 5px;
            margin-bottom: 5px;
        }
        #stopButton {
            width: 60px;
            height: 30px; 
            background-color: yellow; 
            position: relative;
            margin-top: 5px;
            margin-bottom: 5px;
        }
    </style>


    <button id="startButton">START</button>
    <button id="stopButton">STOP</button>
    <svg width="100%" height="100%" version="1.1" viewbox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" id="svg">
        <!--Begin Bottle -->
        <path d="m166.76 57.45c-13.062-0.0623-26.955 0.73204-46.311 0.0859-2.7685-0.0924-5 2.23-5 5v10.709c-2e-5 2.77 2.23 5 5 5h4.7226v6.209a88.388 88.388 0 0 0 -67.176 85.715 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 -88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 88.389 88.388 88.388 0 0 0 0 0 -67.176 -85.695v-6.2285h4.7227c2.77 0 5-2.23 5-5v-10.709c0-2.77-2.231-4.9242-5-5-1.8457-0.0506-3.6945-0.077-5.5606-0.0859z" fill="#1b000c"></path>
        <path d="m231.11 170.17c0 46.793-37.933 84.727-84.727-46.793 0-84.727-37.933-84.727-84.727-1e-6 -40.912 28.997-75.051 67.559-82.986 12.071 2.5421 23.795 1.9463 35.395 0.22531 38.033 8.3382 66.499 42.225 66.499 82.761z" fill="#270600"></path>
        <path d="m122.57 61.1c16.221 0.59986 32.004 0.30589 47.553 0 1.8278-0.036 3.3 1.4718 3.3 3.3v6.2541c0 1.8282-1.4718 3.3-3.3 3.3h-47.553c-1.8282 0-3.3-1.4718-3.3v-6.2541c0-1.8282 1.473-3.3676 3.3-3.3z" fill="#270600"></path>
        <path d="m129.08 77.57v6.0117c9.8102 2.4161 28.289 2.4275 35 0v-6.0117z" fill="#270600"></path>
        <!--End Bottle -->

        <!--Begin Poison Back (continuous operation)-->
        <path fill="#9bc300" id="poi_back">
            <animate id="poi_back_animation" attributename="d" values="m 62.692,157.03 c -0.66726,4.2839 -1.0332,8.6677 -1.0332,13.139 2e-6,46.793 37.933,84.727 84.727,84.727 46.793,0 84.727,-37.933 84.727,-84.727 0,-4.4706 -0.36411,-8.8552 -1.0312,-13.139 -14.83662,12.68631 -46.3415,32.04916 -110.09827,6.15172 C 55.89527,130.25689 61.6596,170.1687 62.6926,157.03 Z; m 62.692,157.03 c 0.858416,-8.12931 -0.379575,2.34105 -1.0332,13.139 -2.827316,46.70751 37.933,84.727 84.727,84.727 46.793,0 84.727,-37.933 84.727,-84.727 0,-4.4706 -0.36411,-8.8552 -1.0312,-13.139 -8.28777,2.68817 -30.19905,-24.60832 -80.45959,1.45473 C 92.556926,187.6518 60.557883,163.01304 61.6588,170.169 Z;m 62.692,157.03 c -0.66726,4.2839 -1.0332,8.6677 -1.0332,13.139 2e-6,46.793 37.933,84.727 84.727,84.727 46.793,0 84.727,-37.9333 84.727,-84.727 0,-4.4706 -0.36411,-8.8552 -1.0312,-13.139 -14.83662,12.68631 -46.3415,32.04916 -110.09827,6.15172 C 55.89527,130.25689 61.6596,170.1687 62.6926,157.03 Z" keytimes="0;0.5;1" begin="0s" automatic start-->
                dur="3s"
                repeatCount="indefinite"
            />
        </animate></path>    
        <!--End Poison Back-->

        <!--Begin Poison Front (Manual Control)-->
        <g id="poi_front">
            <path fill="#739a00">
                <animate id="poi_front_animation" attributename="d" values="m62.692 157.03c-0.66726 4.2839-1.0332 8.6677-1.0332 13.139 2e-6 46.793 37.933 84.727 84.727 84.727 46.793 0 84.727-37.933 84.727-84.727 0-4.4706-0.36411-8.8552-1.0312
">

The above is the detailed content of Precise control and optimization practice of SVG SMIL animation. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 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

PHP Tutorial
1583
276
Essential HTML Tags for Beginners Essential HTML Tags for Beginners Jul 27, 2025 am 03:45 AM

To get started with HTML quickly, you only need to master a few basic tags to build a web skeleton. 1. The page structure is essential, and, which is the root element, contains meta information, and is the content display area. 2. Use the title. The higher the level, the smaller the number. Use tags to segment the text to avoid skipping the level. 3. The link uses tags and matches the href attributes, and the image uses tags and contains src and alt attributes. 4. The list is divided into unordered lists and ordered lists. Each entry is represented and must be nested in the list. 5. Beginners don’t have to force memorize all tags. It is more efficient to write and check them while you are writing. Master the structure, text, links, pictures and lists to create basic web pages.

What is the name attribute in an input tag for? What is the name attribute in an input tag for? Jul 27, 2025 am 04:14 AM

Thenameattributeinaninputtagisusedtoidentifytheinputwhentheformissubmitted;itservesasthekeyinthekey-valuepairsenttotheserver,wheretheuser'sinputisthevalue.1.Whenaformissubmitted,thenameattributebecomesthekeyandtheinputvaluebecomesthevalueinthedatasen

Can you put a  tag inside another  tag? Can you put a tag inside another tag? Jul 27, 2025 am 04:15 AM

❌Youcannotnesttagsinsideanothertagbecauseit’sinvalidHTML;browsersautomaticallyclosethefirstbeforeopeningthenext,resultinginseparateparagraphs.✅Instead,useinlineelementslike,,orforstylingwithinaparagraph,orblockcontainerslikeortogroupmultipleparagraph

HTML `style` Tag: Inline vs. Internal CSS HTML `style` Tag: Inline vs. Internal CSS Jul 26, 2025 am 07:23 AM

The style placement method needs to be selected according to the scene. 1. Inline is suitable for temporary modification of single elements or dynamic JS control, such as the button color changes with operation; 2. Internal CSS is suitable for projects with few pages and simple structure, which is convenient for centralized management of styles, such as basic style settings of login pages; 3. Priority is given to reuse, maintenance and performance, and it is better to split external link CSS files for large projects.

How to embed a PDF document in HTML? How to embed a PDF document in HTML? Aug 01, 2025 am 06:52 AM

Using tags is the easiest and recommended method. The syntax is suitable for modern browsers to embed PDF directly; 2. Using tags can provide better control and backup content support, syntax is, and provides download links in tags as backup solutions when they are not supported; 3. It can be embedded through Google DocsViewer, but it is not recommended to use widely due to privacy and performance issues; 4. In order to improve the user experience, appropriate heights should be set, responsive sizes (such as height: 80vh) and PDF download links should be provided so that users can download and view them themselves.

How to create an unordered list in HTML? How to create an unordered list in HTML? Jul 30, 2025 am 04:50 AM

To create an HTML unordered list, you need to use a tag to define a list container. Each list item is wrapped with a tag, and the browser will automatically add bullets; 1. Create a list with a tag; 2. Each list item is defined with a tag; 3. The browser automatically generates default dot symbols; 4. Sublists can be implemented through nesting; 5. Use the list-style-type attribute of CSS to modify the symbol style, such as disc, circle, square, or none; use these tags correctly to generate a standard unordered list.

How to use the contenteditable attribute? How to use the contenteditable attribute? Jul 28, 2025 am 02:24 AM

ThecontenteditableattributemakesanyHTMLelementeditablebyaddingcontenteditable="true",allowinguserstodirectlymodifycontentinthebrowser.2.Itiscommonlyusedinrichtexteditors,note-takingapps,andin-placeeditinginterfaces,supportingelementslikediv

How to add an icon to your website title tab in HTML How to add an icon to your website title tab in HTML Aug 07, 2025 pm 11:30 PM

To add an icon to the website title bar, you need to link a favicon file in part of the HTML. The specific steps are as follows: 1. Prepare a 16x16 or 32x32 pixel icon file. It is recommended to use favicon.ico to name it and place it in the website root directory, or use modern formats such as PNG and SVG; 2. Add link tags to HTML, such as PNG or SVG formats, adjust the type attribute accordingly; 3. Optionally add high-resolution icons for mobile devices, such as AppleTouchIcon, and specify different sizes through the sizes attribute; 4. Follow best practices, place the icon in the root directory to ensure automatic detection, clear the browser cache after update, and check the correctness of the file path.

See all articles