Home Web Front-end HTML Tutorial How to implement custom path animation in Canvas?

How to implement custom path animation in Canvas?

Jan 19, 2018 am 09:21 AM
canvas customize path

This time I will show you how to implement custom path animation in Canvas? , What are the precautions for implementing custom path animation in Canvas? The following is a practical case, let’s take a look.

In a recent project, the author needs to make a new requirement: implement custom path animation in canvas. The so-called custom path here not only includes a straight line, but may be a combination of motions of multiple straight lines, and even includes Bezier curves

So how can we achieve this animation effect in canvas? In fact, it is very simple. SVG is very good at processing paths. Therefore, to implement custom path animation in canvas, we need to use the power of SVG.

Create Path

Before making animation, we must first get the path of the animation. For this, we can directly use the path definition rules of svg. For example, we define a more complex path (which end You can try it out for yourself, and I won’t show it here). Then, we need to import the defined path into a newly generated path element (we just use the svg API, so we don’t need to insert it into Page)

const path = 'M0,0 C8,33.90861 25.90861,16 48,16 C70.09139,16 88,33.90861 88,56 C88,78.09139 105.90861,92 128,92 C150.09139,92 160,72 160,56 C160,40 148,24 128,24 C108,24 96,40 96,56 C96,72 105.90861,92 128,92 C154,93 168,78 168,56 C168,33.90861 185.90861,16 208,16 C230.09139,16 248,33.90861 248,56 C248,78.09139 230.09139,96 208,96 L48,96 C25.90861,96 8,78.09139 8,56 Z';
 
const pathElement = document.createElementNS('http://www.w3.org/2000/svg',"path");
pathElement.setAttributeNS(null, 'd', path);
getTotalLength与getPointAtLength
Copy after login

The two APIs provided by SVGPathElement are very critical. It can be said that it is the core place to implement path animation (the implementation of custom path animation in svg is generally solved through these two APIs) ) For details, please click: SVGPathElement MDN

getTotalLength method can get the total length of SVGPathElement

getPointAtLength method, passing in a length x, will return the end coordinate of the length x from the starting point of SVGPathElement.

Use these two APIs to continuously update the coordinates of the graphics drawn in the canvas through a loop to achieve path animation:

const length = pathElement.getTotalLength();
const duration = 1000; // 动画总时长
const interval = length / duration;
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
let time = 0, step = 0;
 
const timer = setInterval(function() {
  if (time <= duration) {
    const x = parseInt(pathElement.getPointAtLength(step).x);
    const y = parseInt(pathElement.getPointAtLength(step).y);
    move(x, y);  // 更新canvas所绘制图形的坐标
    step++;
  } else {
    clearInterval(timer)
  }
}, interval);
 
function move(x, y) {
   context.clearRect(0, 0, canvas.width, canvas.height);
   context.beginPath();
   context.arc(x, y, 25, 0, Math.PI*2, true);
   context.fillStyle = &#39;#f0f&#39;;
   context.fill();
   context.closePath();
}
Copy after login

Finally, we encapsulate it. Implement a simple function to implement custom animation in canvas:

function customizePath(path, func) {
    const pathElement = document.createElementNS(&#39;http://www.w3.org/2000/svg&#39;,"path");
    pathElement.setAttributeNS(null, &#39;d&#39;, path);
      const length = pathElement.getTotalLength();
    const duration = 1000;
    const interval = length / duration;
    let time = 0, step = 0;
   
      const timer = setInterval(function() {
        if (time <= duration) {
              const x = parseInt(pathElement.getPointAtLength(step).x);
              const y = parseInt(pathElement.getPointAtLength(step).y);
              func(x, y);
              step++;
        } else {
              clearInterval(timer)
        }
     }, interval);
}
Copy after login
const path = &#39;M0,0 C8,33.90861 25.90861,16 48,16 C70.09139,16 88,33.90861 88,56 C88,78.09139 105.90861,92 128,92 C150.09139,92 160,72 160,56 C160,40 148,24 128,24 C108,24 96,40 96,56 C96,72 105.90861,92 128,92 C154,93 168,78 168,56 C168,33.90861 185.90861,16 208,16 C230.09139,16 248,33.90861 248,56 C248,78.09139 230.09139,96 208,96 L48,96 C25.90861,96 8,78.09139 8,56 Z&#39;;
const canvas = document.querySelector(&#39;canvas&#39;);
const context = canvas.getContext(&#39;2d&#39;);
function move(x, y) {
      context.clearRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
      context.arc(x, y, 25, 0, Math.PI*2, true);
      context.fillStyle = &#39;#f0f&#39;;
      context.fill();
      context.closePath();
}
customizePath(path, move);
Copy after login
The implementation idea is roughly as described above, but this is not the final result. When we decide to create a custom path animation in canvas, we not only have to consider how to implement it, but also

Performance Optimization. For example, in this implementation idea, can we reduce the number of unnecessary renderings? How to control frame rate to achieve optimum? etc.

I believe you have mastered the methods after reading these cases. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

How to implement HTML table mouse drag sorting

What files does html belong to? How to open

HtmlHow to achieve the report effect of dynamically displaying color blocks

The above is the detailed content of How to implement custom path animation in Canvas?. 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 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)

How to quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

Different uses of slashes and backslashes in file paths Different uses of slashes and backslashes in file paths Feb 26, 2024 pm 04:36 PM

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

How to fix error: Main class not found or loaded in Java How to fix error: Main class not found or loaded in Java Oct 26, 2023 pm 11:17 PM

This video cannot be played due to a technical error. (Error Code: 102006) This guide provides simple fixes for this common problem and continue your coding journey. We will also discuss the causes of Java errors and how to prevent it in the future. What is "Error: Main class not found or loaded" in Java? Java is a powerful programming language that enables developers to create a wide range of applications. However, its versatility and efficiency come with a host of common mistakes that can occur during development. One of the interrupts is Error: Main class user_jvm_args.txt not found or loaded, which occurs when the Java Virtual Machine (JVM) cannot find the main class to execute a program. This error acts as a roadblock even in

How to customize shortcut key settings in Eclipse How to customize shortcut key settings in Eclipse Jan 28, 2024 am 10:01 AM

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

The operation process of edius custom screen layout The operation process of edius custom screen layout Mar 27, 2024 pm 06:50 PM

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

What is the difference in the 'My Computer' path in Win11? Quick way to find it! What is the difference in the 'My Computer' path in Win11? Quick way to find it! Mar 29, 2024 pm 12:33 PM

What is the difference in the "My Computer" path in Win11? Quick way to find it! As the Windows system is constantly updated, the latest Windows 11 system also brings some new changes and functions. One of the common problems is that users cannot find the path to "My Computer" in Win11 system. This was usually a simple operation in previous Windows systems. This article will introduce how the paths of "My Computer" are different in Win11 system, and how to quickly find them. In Windows1

How to customize x-axis and y-axis in excel? (How to customize excel axis scale) How to customize x-axis and y-axis in excel? (How to customize excel axis scale) Mar 14, 2024 pm 02:10 PM

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.

Linux kernel source code storage path analysis Linux kernel source code storage path analysis Mar 14, 2024 am 11:45 AM

The Linux kernel is an open source operating system kernel whose source code is stored in a dedicated code repository. In this article, we will analyze the storage path of the Linux kernel source code in detail, and use specific code examples to help readers better understand. 1. Linux kernel source code storage path The Linux kernel source code is stored in a Git repository called linux, which is hosted at [https://github.com/torvalds/linux](http

See all articles