Home  >  Article  >  Web Front-end  >  H5 article: How many ways to implement animation on the page? (with code)

H5 article: How many ways to implement animation on the page? (with code)

奋力向前
奋力向前forward
2021-08-16 17:34:066625browse

In the previous article "html5 articles: 5 ways to achieve page jump (code sharing)", we will show you the 5 ways to use html5 to jump to the current page. The following article will give you an idea of ​​several ways to implement animation on the page. Let’s take a look! !

wed has various animation implementations. With the development of H5, there are more and more ways to implement animation. Preliminary statistics show that the ways to implement animation are as follows.

1. GIF animation

Usually some of the dynamic expressions in our social chats are mostly GIF animations. The original meaning of GIF (Graphics Interchange Format) is "Image Interchange Format". The data of the GIF file is a continuous-tone lossless compression format based on the LZW algorithm. Its compression rate is generally around 50%, and it does not belong to any application. The GIF format can store multiple color images. If the multiple image data stored in a file are read out one by one and displayed on the screen, one of the simplest animations can be formed. GIF is divided into two types: static GIF and animated GIF. The extension is .gif. It is a compressed bitmap format that supports transparent background images. It is suitable for a variety of operating systems. Its "body size" is small. Many small animations on the Internet are GIFs. Format, in fact, GIF saves multiple images into one image file to form an animation. The most common one is a funny gif picture connected through a frame of animation, so in the final analysis, GIF is still a picture file format. GIF production can be done through PS, or through image, video, or FLASH conversion

Disadvantages: High-definition gifs are larger in size. The compressed physical examination will lose frames if it is smaller. The interaction is poor. In essence, it is a moving picture.

2. FLASH animation / SilverLight FLASH

Flash is very powerful, they contain rich videos, sounds, graphics and animations. Flash can be used to create a variety of very gorgeous animations and videos. However, due to various reasons, Flash exited the Android platform on August 15, 2012 and officially bid farewell to the mobile terminal. On December 1, 2015, Adobe upgraded the animation production software Flashprofessional CC2015 and renamed it Animate CC 2015.5, thus drawing a clear line with Flash technology. A long time ago, the large picture carousels on the homepages of various corporate portals basically used flash. In the early years, the large pictures at the top of the homepage of 12306's ticket purchase website also used flash, but now they are all replaced by static pictures. This technology has gradually faded out of sight, and only online video live broadcasts such as Youku, iQiyi and other video websites are available.

Disadvantages: It is played based on flash player. Flash player is very performance-consuming and often reports various vulnerabilities.

SilverLight

Microsoft Silverlight is a cross-browser, cross-platform plug-in and a new Web rendering technology , can run on various platforms. With this technology, you have a rich, visually stunning interactive experience that is consistent whether within a browser or across desktop operating systems such as Windows and Apple Macintosh .

Disadvantages: Supporting animation in the form of browser plug-ins is not easy to develop. It’s enough to understand that this stuff is there Copyright belongs to the author.

3. Javascript HTML

Principle: The main idea is to continuously call and change the CSS style of an element through the callback function of the setInterval or setTimeout method to achieve the effect of changing the element style.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <style type="text/css">
      #animate {
        width: 200px;
        height: 200px;
        background: #ccc;
      }
    </style>
  </head>
  <body>
    <div id="animate"></div>
    <script>
      let elem = document.getElementById("animate");
      let left = 0;
      let timer = setInterval(function () {
        if (left < window.innerWidth - 200) {
          elem.style.marginLeft = left + "px";
          left++;
        } else {
          clearInterval(timer);
        }
      }, 16); //这里的16毫秒
    </script>
  </body>
</html>

Jquery’s animate() method is implemented in this way.

Disadvantages: Implementing animations in JavaScript usually results in frequent page rearrangements and redraws, which consumes performance. Generally, it should be used in desktop browsers. There will be obvious lag when used on the mobile terminal.

16ms problem: It is generally believed that the smooth animation that the human eye can recognize is 60 frames per second, here the 16ms ratio is (1000ms/60) The frames are slightly smaller, but the animation is still generally smooth. When optimizing the performance of many mobile animations, 16ms is generally used to throttle and process continuously triggered browser events. For example, throttling touchmove and scroll events. By reducing the triggering frequency of continuous events in this way, the smoothness of animation can be greatly improved.

4. SMIL

SMIL features: The program starts with and ends with. The entire program consists of two parts: body and head. SMIL requires that its tags and tag attributes must be lowercase! Some tags must have a slash as the closing tag, the attribute value must be enclosed in double quotes, and the extension of the SMIL file is *.smil or *.smi.

<smil>
  <head></head>

  <body>
    <seq>
      <!-- 演示开始进行2秒后开始显示,持续播放5秒 -->
      <img  src="1.jpg" dur="5s" begin="2" / alt="H5 article: How many ways to implement animation on the page? (with code)" >
      <!-- 演示开始进行3秒后开始显示,持续播放10秒 -->
      <img  src="2.jpg" dur="10s" bengin="3" / alt="H5 article: How many ways to implement animation on the page? (with code)" >
      <!-- 演示开始进行5秒后开始显示,在整个演示播放40秒以后,就结束播放 -->
      <video src="test.rm" begin="5s" end="40s" />
      <!-- 只播放视频文件的第5秒到第10秒,重复播放2次 -->
      <video src="test.rm" clip-begin="5s" clip-end="10s" repeat="2" />
    </seq>
  </body>
</smil>

Embed html

Add a namespace definition to the tag, add a &lt ;?import> element to import the "time" namespace and add a <style></style>element## that defines the "time" class #

<html xmlns:time="urn:schemas-microsoft-com:time">
  <head>
    <?import namespace="time" implementation="#default#time2">
    <style>
      .time {
        behavior: url(#default#time2);
      }
    </style>
  </head>

  <body>
    <!-- repeatCount循环次数 -->
    <time:seq repeatCount="indefinite">
      <img  class="time" src="image1.jpg" dur="3s" / alt="H5 article: How many ways to implement animation on the page? (with code)" >
      <img  class="time" src="image2.jpg" dur="3s" / alt="H5 article: How many ways to implement animation on the page? (with code)" >
    </time:seq>
  </body>
</html>

Disadvantages: You can tell at a glance that it only supports IE. Nothing to say

五、APNG 

APNG, 全称是“Animated Portable Network Graphics”, 是PNG的位图动画扩展,他和 gif 的区别在于:图片质量,gif最多支持 256 种颜色,不支持Alpha透明通道。可以称之为色彩丰富支持Alpha透明通道体积大小和 gif 甚至更小的 gif。 2007 年 4 月 20日,PNG组织投票以 10:8 否决APNG进入官方标准。也就是PNG不认可他。 

缺点:Chrome 59 之后,只有 IE 不支持。

APNG的制作:http://littlesvr.ca/apng/

六、Javascript + SVG

SVG的动画元素是和SMIL开发组合作开发的。SMIL开发组和SVG开发组合作开发了SMIL动画规范,在规范中制定了一个基本的XML动画特征集合。SVG吸收了SMIL动画规范当中的动画优点,并提供了一些SVG继承实现。

特性

  • SVG 指可伸缩矢量图形 (Scalable Vector Graphics)

  • SVG 用来定义用于网络的基于矢量的图形

  • SVG 使用 XML 格式定义图形

  • SVG 图像在放大或改变尺寸的情况下其图形质量不会有所损失

  • SVG 是万维网联盟的标准

  • SVG 与诸如 DOM 和 XSL 之类的 W3C 标准是一个整体

SVG animation最强大的地方在于:™ 只要在页面放几个animate元素,没有任何CSS, 没有任何JS,页面上的元素就像是没吃草的马儿一样,愉快地跑起来了。你会发现,我勒个去,原来要实现个动画效果这么简单。什么CSS3动画,哪边凉快哪边呆着吧!

<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
  <g>
    <text font-family="microsoft yahei" font-size="120" y="160" x="160">
      哈哈
    </text>
    <animateTransform
      attributeName="transform"
      begin="0s"
      dur="10s"
      type="rotate"
      from="0 160 160"
      to="360 160 160"
      repeatCount="indefinite"
    />
  </g>
</svg>

元素

<set></set>此元素没有动画效果,可以在特定时间之后修改某个属性值(也可以是CSS属性值)

<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
  <g>
    <text font-family="microsoft yahei" font-size="120" y="160" x="160">
      测试
      <!-- 3秒后把x值改为60 -->
      <set attributeName="x" attributeType="XML" to="60" begin="3s" />
    </text>
  </g>
</svg>

<animate></animate>基础动画元素。实现单属性的动画过渡效果

<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
  <g>
    <text font-family="microsoft yahei" font-size="120" y="160" x="160">
      测试
      <!-- 从0秒开始,总时长3秒,x值从160到60,(repeatCount)不间断循环 -->
      <animate
        attributeName="x"
        from="160"
        to="60"
        begin="0s"
        dur="3s"
        repeatCount="indefinite"
      />
    </text>
  </g>
</svg>

<animatecolor></animatecolor>颜色动画,因为 animate 能实现其功能,所以被废弃了。逝者已矣...

<animatetransform></animatetransform>实现 transform 变换动画效果的,与 CSS3 的 transform 变换是一个套路

<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
  <g>
    <text font-family="microsoft yahei" font-size="80" y="100" x="100">
      测试
    </text>
    <!-- 从0秒开始,总时长3秒,变换类型为scale(缩放),值从1到1.5,repeatCount)不间断循环  -->
    <animateTransform
      attributeName="transform"
      begin="0s"
      dur="3s"
      type="scale"
      from="1"
      to="1.5"
      repeatCount="indefinite"
    />
  </g>
</svg>

<animatemotio></animatemotio>元素可以让 SVG 各种图形沿着特定的 path 路径运动~

<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
  <text font-family="microsoft yahei" font-size="30" x="0" y="0" fill="green">
    动
    <!-- 从0秒开始,总时长3秒,不间断循环,沿着路径path运动 -->
    <animateMotion
      path="m124.067754,67.21128c39.580339,-101.001223 194.657404,0 0,129.858716c-194.657404,-129.858716 -39.580339,-230.859939 0,-129.858716z"
      begin="0s"
      dur="5s"
      rotate="auto"
      repeatCount="indefinite"
    />
  </text>
  <path
    d="m124.067754,67.21128c39.580339,-101.001223 194.657404,0 0,129.858716c-194.657404,-129.858716 -39.580339,-230.859939 0,-129.858716z"
    stroke-width="1.5"
    stroke="#cd0000"
    fill="none"
  />
</svg>

展示的时候是这个样子的

H5 article: How many ways to implement animation on the page? (with code)

暂停和播放

// svg指当前svg DOM元素
// 暂停
svg.pauseAnimations();

// 重启动
svg.unpauseAnimations();

关于 svg 的之后再写文章详细介绍吧

七、Video

<video></video>是HTML 5的新标签

<video src="movie.ogg" controls="controls">
  您的浏览器不支持 video 标签。
</video>

相关属性

属性 描述
autoplay autoplay 如果出现该属性,则视频在就绪后马上播放。
controls controls 如果出现该属性,则向用户显示控件,比如播放按钮。
height pixels 设置视频播放器的高度。
loop loop 如果出现该属性,则当媒介文件完成播放后再次开始播放。
preload preload 如果出现该属性,则视频在页面加载时进行加载,并预备播放。如果使用 "autoplay",则忽略该属性。
src url 要播放的视频的 URL。
width pixels 设置视频播放器的宽度。

八、Javascript + Canvas

canvas作为H5新增元素,是借助Web API来实现动画的。 结合setInterval或者requestAnimationFrame可以实现各种样的动画,下面的例子展示了一个 7 色圆的颜色过度

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>JS Bin</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script>
      function colorPalette(gradient) {
        var canvas = document.createElement("canvas");
        canvas.width = "1";
        canvas.height = "256";
        // document.body.appendChild(canvas); // debug
        var ctx = canvas.getContext("2d"),
          grad = ctx.createLinearGradient(0, 0, 1, 256);
        gradient.forEach(function (item) {
          grad.addColorStop(item[0], item[1]);
        });
        ctx.fillStyle = grad;
        ctx.fillRect(0, 0, 1, 256);
        return ctx.getImageData(0, 0, 1, 256).data;
      }

      (function () {
        var palette = colorPalette([
          [0, "red"],
          [0.7, "orange"],
          [0.17, "yellow"],
          [0.22, "green"],
          [0.42, "cyan"],
          [0.82, "blue"],
          [0.9, "purple"],
        ]);

        // Canvas元素
        var canvas = document.querySelector("canvas");
        var context = canvas.getContext("2d");
        var width = canvas.width,
          height = canvas.height;
        var start = Date.now();
        // 绘制方法
        var draw = function () {
          context.clearRect(0, 0, width, height);
          // 计算偏移
          var offset = Math.floor((Date.now() - start) / (3300 / 256)) % 256;
          context.fillStyle =
            "rgba(" +
            [
              palette[offset * 4 + 0],
              palette[offset * 4 + 1],
              palette[offset * 4 + 2],
              palette[offset * 4 + 3],
            ] +
            ")";
          context.arc(width / 2, height / 2, height / 2, 0, 2 * Math.PI);
          context.fill();
          // 持续变化
          requestAnimationFrame(draw);
        };
        draw();
      })();
    </script>
  </body>
</html>

复制下面链接在线看demo:

https://jsbin.com/piwihur/edit?html,js,output

cavans有些复杂,一时半会消化不了。之后再写详细的文章研究。Canvas主要优势是可以应对页面中多个动画元素渲染较慢的情况,完全通过javascript来渲染控制动画的执行。可用于实现较复杂动画

九、CSS3 transition/animation

transition

transition是过度动画。但是transition并不能实现独立的动画,只能在某个标签元素样式或状态改变时进行平滑的动画效果过渡,而不是马上改变。

在移动端开发中,直接使用transition动画会让页面变慢甚至卡顿。所以我们通常添加transform:translate3D(0,0,0)或transform:translateZ(0)来开启移动端动画的GPU加速,让动画过程更加流畅。

animation

animation算是真正意义上的CSS3动画。通过对关键帧和循环次数的控制,页面标签元素会根据设定好的样式改变进行平滑过渡。而且关键帧状态的控制是通过百分比来控制的。

CSS3最大的优势是摆脱了js的控制,并且能利用硬件加速以及实现复杂动画效果。

有一篇文章做了简单的介绍,点这里

假如用CSS3来实现上面的Canvas7 彩颜色过渡的话,就非常简单了

@keyframes color {
  0% {
    background-color: red;
  }
  7% {
    background-color: orange;
  }
  17% {
    background-color: yellow;
  }
  22% {
    background-color: green;
  }
  42% {
    background-color: cyan;
  }
  82% {
    background-color: blue;
  }
  90% {
    background-color: purple;
  }
}

当然并不是用CSS3做动画比Canvas牛逼,只是使用场景不一样吧。 知道的就这些了,之后再补充吧。

 [完] 

推荐学习:SVG视频教程

The above is the detailed content of H5 article: How many ways to implement animation on the page? (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:chuchur.com. If there is any infringement, please contact admin@php.cn delete