Use chatGPT to realize digital auto-increment animation

num-auto-add: Number auto-increment animation

preamble

We often encounter digital self-increasing animation effects on some good websites, which provide users with a richer interactive experience and look very cool.

Please add a picture description

I also wrote it before, and for the convenience of future use, I plan to optimize it and upload it to npm.

The first step is to hand over the code to chatGPT for optimization.

It can be found that, except for the change of the timer interval, there is not much change

Please add a picture description

Continue to optimize chatGPT. At this time, it changes the animation effect from timer to requestAnimationFrame. The animation effect is smoother, which is really good.

Please add a picture description

Seeing it output a lot, I thought it was awesome, but when I ran the code, it turned out that it couldn't run.

In general, chatGPT can only assist in writing code at present, and errors will occur if the logic is a little more complicated, including code comments, which are problematic, and you still have to modify it by yourself.

The address of the final small demo is: num-auto-add - npm (npmjs.com) , everyone is welcome to download and use it.

Use the tutorial (example in the vue project)

1. Download package

  • download with yarnyarn add num-auto-add
  • Download with npmnpm i num-auto-add

2. Import package

import numAutoAdd from "num-auto-add";

3. Declare custom directives

Vue.directive('numAutoAdd', numAutoAdd());

Note: numAutoAdd can function receive two parameters

  • The first parameter is to set the total time for animation execution (in milliseconds), the default is 700ms
  • The second parameter is the Boolean flag many, which is used to indicate whether the animation can be executed multiple times or only once. The default is true, that is, it can be executed multiple times.

4. Bind instructions to numbers

Please add a picture description

At this point, the digital self-increment effect is realized, and it is very simple to use

Realization principle

The source code is as follows:

export default function(totalTime = 700, many = true) {
  function animateNumber(el, finalNum, startTime) {
    const currentTime = Date.now();
    const runTime = currentTime - startTime; // 运行时间
    const progress = Math.min(runTime / totalTime, 1); // 动画进度
    el.innerHTML = Math.floor(finalNum * progress); // 当前页面显示的数字
    if (runTime < totalTime) {
      requestAnimationFrame(() => animateNumber(el, finalNum, startTime));
    }
  }
  return {
    // 当被绑定的元素插入到 DOM 时调用
    inserted: function(el, binding) {
      // flag用来判断是否能执行动画,防止一个时间段内触发多次动画函数
      binding.flag = true;
      // 元素在可视区域内才开始执行动画的函数
      binding.animate = () => {
        // 获取元素距离可视区域顶部的距离
        const top = el.getBoundingClientRect().top;
        // 获取浏览器可视区域的高度(这里考虑了浏览器兼容的问题)
        const h =
          document.documentElement.clientHeight || document.body.clientHeight;
        // 当元素在可视区域内
        if (top < h) {
          // 如果动画没在执行
          if (binding.flag) {
            binding.flag = false;
            const finalNum = el.innerHTML; // 要显示的真实数值
            animateNumber(el, finalNum, Date.now()); // 执行数字自增动画
            // 如果只执行一次动画,则解绑滚动事件
            !many && window.removeEventListener("scroll", binding.animate);
          }
        } else {
          binding.flag = true;
        }
      };
      window.addEventListener("scroll", binding.animate);
    },
    // 自定义绑定的组件销毁时,关闭监听器
    unbind: function(el, binding) {
      window.removeEventListener("scroll", binding.animate);
    }
  };
}

inserted

The inserted property is a function that is called when the element is inserted into the DOM. Add a scroll event to the window, and the callback function is animate, which will be executed every time the mouse is rolled.

window.removeEventListener("scroll", binding.animate)

The animate function checks to see if the element appears within the visible area. Once the element enters the viewport, the "number auto-increment animation" animateNumber is called

if (top < h) {
  // 如果动画没在执行
  if (binding.flag) {
    binding.flag = false;
    const finalNum = el.innerHTML; // 要显示的真实数值
    animateNumber(el, finalNum, Date.now()); // 执行数字自增动画
    // 如果只执行一次动画,则解绑滚动事件
    !many && window.removeEventListener("scroll", binding.animate);
 }

animateNumber is a function that calculates the progress of the animation and updates the current value of the element.

  function animateNumber(el, finalNum, startTime) {
    const currentTime = Date.now();
    const runTime = currentTime - startTime; // 运行时间
    const progress = Math.min(runTime / totalTime, 1); // 动画进度
    el.innerHTML = Math.floor(finalNum * progress); // 当前页面显示的数字
    if (runTime < totalTime) {
      requestAnimationFrame(() => animateNumber(el, finalNum, startTime));
    }
  }

unbind

The unbind property is a function that is called when the custom bound component is destroyed. This function will unbind the scroll event to avoid occupying resources.

  // 自定义绑定的组件销毁时,关闭监听器
  unbind: function(el, binding) {
    window.removeEventListener("scroll", binding.animate);
  }

Summarize

The achievements of chatGPT in programming are very remarkable. It not only created a new era of human-computer interaction, but also brought new ideas and methods to the development of technology. Using chatGPT to assist in writing code is the general trend. In addition, it can also assist us in writing articles, for example, part of the content of the article is generated using AI .

Guess you like

Origin blog.csdn.net/qq_52607834/article/details/129759467