css动画和js动画

How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps?

基于JavaScript的动画怎么可能总是秘密地一直比CSS转换快或快? 而且,Adobe和Google如何持续发布可与本地应用程序性能相媲美的富媒体移动网站?

This article serves as a point-by-point walkthrough of how JavaScript-based DOM animation libraries, such as Velocity.js and GSAP, are more performant than jQuery and CSS-based animation libraries.

本文逐步介绍了基于JavaScript的DOM动画库(例如Velocity.js和GSAP)如何比基于jQuery和CSS的动画库更高效。

jQuery的 (jQuery)

Let's start with the basics: JavaScript and jQuery are falsely conflated. JavaScript animation is fast. jQuery slows it down. Why? Because — despite jQuery being tremendously powerful — it was never jQuery's design goal to be a performant animation engine:

让我们从基础开始:错误地合并JavaScript和jQuery。 JavaScript动画速度很快。 jQuery减慢了速度。 为什么? 因为尽管jQuery非常强大,但成为高性能动画引擎从来都不是jQuery的设计目标:

  • jQuery cannot avoid layout thrashing due to its codebase that serves many purposes beyond animation.

    jQuery由于其代码库的功能超出了动画,因此无法避免布局混乱 。

  • jQuery's memory consumption frequently triggers garbage collections that momentarily freeze animations.

    jQuery的内存消耗经常触发垃圾收集,这些垃圾收集会暂时冻结动画 。

  • jQuery uses setInterval instead of requestAnimationFrame (RAF) in order to protect novices from themselves.

    jQuery使用setInterval而不是requestAnimationFrame(RAF) 来保护新手不受其攻击 。

Note that layout thrashing is what causes stuttering at the start of animations, garbage collection is what causes stuttering during animations, and the absence of RAF is what generally produces low frame rates.

请注意,布局抖动是导致动画开始时出现卡顿的原因,垃圾收集是导致动画期间发生卡顿的原因,而缺少RAF则通常会导致帧率降低。

实施实例 (Implementation Examples)

Avoiding layout thrashing consists of simply batching together DOM queries and DOM updates:

避免布局颠簸包括简单地将DOM查询和DOM更新批处理在一起:


var currentTop,
currentLeft;
/* With layout thrashing. */
currentTop = element.style.top; /* QUERY */
element.style.top = currentTop + 1; /* UPDATE */
currentLeft = element.style.left; /* QUERY */
element.style.left = currentLeft + 1; /* UPDATE */
/* Without layout thrashing. */
currentTop = element.style.top; /* QUERY */
currentLeft = element.style.left; /* QUERY */
element.style.top = currentTop + 1; /* UPDATE */
element.style.left = currentLeft + 1; /* UPDATE */

Queries that take place after an update force the browser to recalculate the page's computed style data (while taking the new update's effects into consideration). This produces significant overhead for animations that are running over tiny intervals of just 16ms.

更新之后发生的查询会强制浏览器重新计算页面的计算样式数据(同时考虑新更新的影响)。 对于仅以16ms的微小间隔运行的动画,这会产生大量开销。

Similarly, implementing RAF doesn't necessitate a significant reworking of your existing codebase. Let's compare the basic implementation of RAF against that of setInterval:

同样,实施RAF无需对现有代码库进行大量修改。 让我们将RAF的基本实现与setInterval的实现进行比较:


var startingTop = 0;
/* setInterval: Runs every 16ms to achieve 60fps (1000ms/60 ~= 16ms). */
setInterval(function() {
/* Since this ticks 60 times a second, we divide the top property's increment of 1 unit per 1 second by 60. */
element.style.top = (startingTop += 1/60);
}, 16);
/* requestAnimationFrame: Attempts to run at 60fps based on whether the browser is in an optimal state. */
function tick () {
element.style.top = (startingTop += 1/60);
}
window.requestAnimationFrame(tick);

RAF produces the biggest possible boost to animation performance that you could make with a single change to your code.

通过对代码进行一次更改,RAF可以最大程度地提高动画性能。

CSS过渡 (CSS Transitions)

CSS transitions outperform jQuery by offloading animation logic to the browser itself, which is efficient at 1) optimizing DOM interaction and memory consumption to avoid stuttering, 2) leveraging the principles of RAF under the hood and 3) forcing hardware acceleration (leveraging the power of the GPU to improve animation performance).

CSS通过将动画逻辑转移到浏览器本身来实现优于jQuery的转换,效率很高:1)优化DOM交互和内存消耗以避免卡顿; 2)充分利用RAF的原理; 3)强制硬件加速(利用GPU来提高动画性能)。

The reality, however, is that these optimizations can also be performed directly within JavaScript. GSAP has been doing it for years. Velocity.js, a new animation engine, not only leverages these same techniques but also goes several steps beyond -- as we'll explore shortly.

但是现实是,这些优化也可以直接在JavaScript中执行。 GSAP已经这样做了多年。 Velocity.js是一种新的动画引擎,不仅利用了这些相同的技术,而且还超越了其他几个步骤-稍后我们将进行探讨。

Coming to terms with the fact that JavaScript animation can rival CSS animation libraries is only step one in our rehab program. Step two is realizing that JavaScript animation can actually be faster than them.

JavaScript动画可以与CSS动画库媲美这一事实只是我们修复程序中的第一步。 第二步是意识到JavaScript动画实际上可以比它们更快。

Let's start by examining the weaknesses of CSS animation libraries:

让我们从检查CSS动画库的弱点开始:

  • Transitions' forced hardware acceleration taxes GPU's, resulting in stuttering and banding in high-stress situations. These effects are exacerbated on mobile devices. (Specifically, the stuttering is a result of the overhead that occurs when data is transferred between the browser's main thread and its compositor thread. Some CSS properties, like transforms and opacity, are immune to this overhead.) Adobe elaborates on this issue here.

    过渡的强制硬件加速使GPU负担重,导致在高压力情况下出现卡顿和条带化。 这些影响在移动设备上更加严重。 (特别是,口吃是由于在浏览器的主线程与其合成线程之间进行数据传输时产生的开销的结果。某些CSS属性(例如,transform和opacity)不受此开销的影响。)Adobe在这里详细说明了这一问题。

  • Transitions do not work below Internet Explorer 10, causing accessibility problems for desktop sites since IE8 and IE9 remain very popular.

    在Internet Explorer 10下过渡无法正常工作,因为IE8和IE9仍然很受欢迎 ,从而导致桌面站点的可访问性问题。

  • Because transitions aren't natively controlled by JavaScript (they are merely triggered by JavaScript), the browser does not know how to optimize transitions in sync with the JavaScript code that manipulates them.

    因为过渡不是由JavaScript本身控制的(它们只是由JavaScript 触发 ),所以浏览器不知道如何与操纵它们JavaScript代码同步地优化过渡。

Conversely: JavaScript-based animation libraries can decide for themselves when to enable hardware acceleration, they inherently work across all versions of IE, and they're perfectly suited for batched animation optimizations.

相反,基于JavaScript的动画库可以自行决定何时启用硬件加速,它们固有地可以在所有版本的IE上运行,并且非常适合批处理动画优化。

My recommendation is to use raw CSS transitions when you're exclusively developing for mobile and your animations consist solely of simple state changes. In such circumstances, transitions are a performant and native solution that allow you to retain all animation logic inside your stylesheets and avoid bloating your page with JavaScript libraries. However, if you're designing intricate UI flourishes or are developing an app with a stateful UI, always use an animation library so that your animations remain performant and your workflow remains manageable. One library in particular that does a fantastic job at managing CSS transitions is Transit.

我的建议是在专门为移动设备开发且动画仅包含简单的状态更改时使用原始CSS过渡。 在这种情况下,过渡是一种高效且本机的解决方案,使您可以将所有动画逻辑保留在样式表中,并避免使用JavaScript库使页面膨胀。 但是,如果您正在设计复杂的UI或正在开发具有状态UI的应用程序,请始终使用动画库,以使动画保持高性能,并使工作流程可管理。 Transit 是一个在管理CSS过渡方面做得非常出色的库

JavaScript动画 (JavaScript Animation)

Okay, so JavaScript can have the upper hand when it comes to performance. But exactly how much faster can JavaScript be? Well — to start — fast enough to build an intense 3D animation demo that you typically only see built with WebGL. And fast enough to build a multimedia teaser that you typically only see built with Flash or After Effects. And fast enough to build a virtual world that you typically only see built with canvas.

好的,因此JavaScript可以在性能方面占上风。 但是JavaScript到底能快多少呢? 好了-开始-足够快地构建一个密集的3D动画演示 ,您通常只能在WebGL中看到该演示 。 而且速度足够快,可以构建通常仅使用Flash或After Effects构建的多媒体预告片 。 而且构建一个虚拟世界的速度足够快,通常您只能看到使用画布构建的虚拟世界 。

To directly compare the performance of leading animation libraries, including Transit (which uses CSS transitions), head on over to Velocity's documentation at VelocityJS.org.

直接比较的领先动画库,包括交通(使用CSS转换),头部到Velocity的文档表现VelocityJS.org 。

The question remains: How exactly does JavaScript reach its high levels of performance? Below is a short list of optimizations that JavaScript-based animation is capable of performing:

问题仍然存在:JavaScript如何精确地达到其高性能水平? 以下是基于JavaScript的动画能够执行的优化的简短列表:

  • Synchronizing the DOM → tween stack across the entirety of the animation chain in order to minimize layout thrashing.在整个动画链中同步DOM→补间堆栈,以最大程度地减少布局抖动。
  • Caching property values across chained calls in order to minimize the occurrence of DOM querying (which is the Achilles' heel of performant DOM animation).跨链接调用缓存属性值,以最大程度地减少DOM查询的发生(这是高性能DOM动画的致命弱点)。
  • Caching unit conversion ratios (e.g. px to %, em, etc.) across sibling elements in the same call.在同一调用中跨兄弟元素缓存单位转换率(例如px到%,em等)。
  • Skipping style updating when updates would be visually imperceptible.如果在视觉上看不到更新,则跳过样式更新。

Revisiting what we learned earlier about layout thrashing, Velocity.js leverages these best practices to cache the end values of an animation to be reused as the start values of the ensuing animation — thus avoiding requerying the DOM for the element's start values:

回顾我们之前学习的有关布局颠簸的知识,Velocity.js利用这些最佳实践来缓存动画的结束值,以将其作为后续动画的开始值重用-从而避免为元素的开始值重新查询DOM:


$element
/* Slide the element down into view. */
.velocity({ opacity: 1, top: "50%" })
/* After a delay of 1000ms, slide the element out of view. */
.velocity({ opacity: 0, top: "-50%" }, { delay: 1000 });

In the above example, the second Velocity call knows that it should automatically start with an opacity value of 1 and a top value of 50%.

在上面的示例中,第二个Velocity调用知道它应该自动从不透明度值1和最高值50%开始。

The browser could ultimately perform many of these same optimizations itself, but doing so would entail aggressively narrowing the ways in which animation code could be crafted by the developer. Accordingly, for the same reason that jQuery doesn't use RAF (see above), browsers would never impose optimizations that have even a tiny chance of breaking spec or deviating from expected behavior.

浏览器最终可能会自己执行许多相同的优化操作,但是这样做将极大地缩小开发人员制作动画代码的方式。 因此,出于与jQuery不使用RAF相同的原因(请参见上文),浏览器将永远不会进行优化,甚至可能极少有违反规格或偏离预期行为的优化。

Finally, let's compare the two JavaScript animation libraries (Velocity.js and GSAP) against one another.

最后,让我们将两个JavaScript动画库(Velocity.js和GSAP)相互比较。

  • GSAP is a fast, richly-featured animation platform. Velocity is a lightweight tool for drastically improving UI animation performance and workflow.GSAP是一个快速,功能丰富的动画平台。 Velocity是一种轻量级的工具,可以极大地改善UI动画性能和工作流程。
  • GSAP requires a licensing fee for various types of businesses. Velocity is freely open-sourced via the ultra-permissive MIT license.

    GSAP要求为各种类型的企业支付许可费 。 Velocity是通过超许可的MIT许可证免费开源的。

  • Performance-wise, GSAP and Velocity are indistinguishable in real-world projects. 在性能方面,GSAP和Velocity在实际项目中是无法区分的。

My recommendation is to use GSAP when you require precise control over timing (e.g. remapping, pause/resume/seek), motion (e.g. bezier curve paths), or complex grouping/sequencing. These features are crucial for game development and certain niche applications, but are less common in web app UI's.

我的建议是当您需要精确控制时序(例如重新映射,暂停/继续/搜索),运动(例如贝塞尔曲线路径)或复杂的分组/排序时,请使用GSAP。 这些功能对于游戏开发和某些特定领域的应用程序至关重要,但是在Web应用程序UI中并不常见。

Velocity.js (Velocity.js)

Referencing GSAP's rich feature set is not to imply that Velocity itself is light on features. To the contrary. In just 7Kb when zipped, Velocity not only replicates all the functionality of jQuery's $.animate(), but it also packs in color animation, transforms, loops, easings, class animation, and scrolling.

引用GSAP的丰富功能集并不意味着Velocity本身就是轻量级功能。 与此相反的。 在压缩后仅7Kb的速度,Velocity不仅复制了jQuery $.animate()所有功能,而且还打包了彩色动画,变换,循环,缓动,类动画和滚动。

In short, Velocity is the best of jQuery, jQuery UI, and CSS transitions combined.

简而言之,Velocity是jQuery,jQuery UI和CSS过渡的最佳结合。

Further, from a convenience viewpoint, Velocity uses jQuery's $.queue() method under the hood, and thus interoperates seamlessly with jQuery's $.animate(), $.fade(), and $.delay() functions. And, since Velocity's syntax is identical to $.animate()'s, none of your page's code needs to change.

此外,从方便的角度来看,Velocity在$.queue()使用了jQuery的$.queue()方法,因此可以与jQuery的$.animate()$.fade()$.delay()函数无缝地互操作。 而且,由于Velocity的语法与$.animate()的语法相同,因此$.animate() 更改页面的代码

Let's take a quick look at Velocity.js. At a basic level, Velocity behaves identically to $.animate():

让我们快速浏览一下Velocity.js。 在基本级别上,Velocity的行为与$.animate()相同:


$element
.delay(1000)
/* Use Velocity to animate the element's top property over a duration of 2000ms. */
.velocity({ top: "50%" }, 2000)
/* Use a standard jQuery method to fade the element out once Velocity is done animating top. */
.fadeOut(1000);

At its most advanced level, complex scrolling scenes with 3D animations can be created — with merely two simple lines of code:

在其最高级的级别上,可以创建带有3D动画的复杂滚动场景-只需两行简单的代码即可:


$element
/* Scroll the browser to the top of this element over a duration of 1000ms. */
.velocity("scroll", 1000)
/* Then rotate the element around its Y axis by 360 degrees. */
.velocity({ rotateY: "360deg" }, 1000);

结语 (Wrapping Up)

Velocity's goal is to remain a leader in DOM animation performance and convenience. This article has focused on the former. Head on over to VelocityJS.org to learn more about the latter.

Velocity的目标是保持DOM动画性能和便利性方面的领导者。 本文重点讨论前者。 前往VelocityJS.org进一步了解后者。

Before we conclude, remember that a performant UI is about more than just choosing the right animation library. The rest of your page should also be optimized. Learn more from these fantastic Google talks:

在得出结论之前,请记住, 高性能的UI不仅仅是选择正确的动画库 。 页面的其余部分也应进行优化。 从这些精彩的Google讲座中了解更多信息:

  • Jank Free

    垃圾免费

  • Rendering Without Lumps

    无肿块渲染

  • Faster Websites

    更快的网站

翻译自: https://davidwalsh.name/css-js-animation

css动画和js动画


http://www.taodudu.cc/news/show-2895996.html

相关文章:

  • silver searcher ag 命令文档
  • 兼容性运行程序永远_永远不会有太多的应用程序
  • Sixth season fifteenth and sixteenth episode,things that could have been......(没有如果)
  • Goldsrc 地图 BSP 文件格式规范
  • 【文献阅读】 Sorghum segmentation by skeleton extraction
  • Matplotlib和Seaborn(离散数据的图表选择与一些使用技巧)
  • 基于ImagePy工具的岩块图像二值化分割研究
  • k8s-数据卷
  • Python Behave框架学习
  • first season ninth episode, 所有人的感恩节都很糟糕
  • OpenSIPS 3.1 开发手册(二)--SIP消息及Opensips配置文件
  • OpenSIPS实战(八):修改sip消息-使用lumps system
  • opencv微信二维码引擎的使用(for java)
  • 分页器
  • ZSTU2019校赛 Problem D Lis(线性基dp)
  • [UnexpectedValueException] Your github oauth token for github.com contains invalid characters
  • 由OJ提交结果联想到内存页面大小的一些小猜想
  • Spring当中循环依赖很少有人讲,今天一起来学习!
  • 帮助你更好的理解Spring循环依赖
  • Spring当中循环依赖很少有人讲,今天让我们来看看吧
  • spring循环依赖让你更好的理解spring!!
  • 探针一号的SQL注入学习笔记
  • 微信获取nickname mysql乱码_微信nickname乱码(emoji)及mysql编码格式设置(utf8mb4)解决的过程...
  • 第四阶段微服务
  • 队列的基本操作
  • 高级版的 jvisualvm :Spring Boot Admin 监控 Spring Boot 微服务项目
  • java的“看门狗”锁续期可以用php redis这样实现【php锁续期、分布式锁、无锁请求队列超卖】解决【商家超卖(商品库存控制)、用户超买(秒杀订单控制)】问题。非demo 线上一直在用
  • 九度oj 题目1080:进制转换
  • 【杭电oj】2089 - 不要62(打表)
  • Jarvis OJ BASIC部分题目writeup

css动画和js动画_CSS与JS动画:哪个更快?相关推荐

  1. css动画 和 js动画_CSS大师的动画建议

    css动画 和 js动画 Just over a week ago we were lucky enough to have Tiffany Brown join us on the SitePoin ...

  2. CSS 和 JS 动画哪个更快

    基于Javascript的动画暗中同CSS过渡效果一样,甚至更加快,这怎么可能呢?而Adobe和Google持续发布的富媒体移动网站的性能可媲美本地应用,这又怎么可能呢? 本文逐一遍览了基于Javas ...

  3. 使用HTML+CSS+JS模拟比赛晋级的动画功能

    使用HTML+CSS+JS模拟比赛晋级的动画功能 1.需求描述 2.代码实现 3.效果演示 系统:Win10 Chrome:106.0.5249.119 演示视频:[英雄联盟]S12全球总决赛冠军预测 ...

  4. 短视频带货系统,HTML+CSS+JS实现宇宙星球旋转动画特效

    短视频带货系统,HTML+CSS+JS实现宇宙星球旋转动画特效 主要代码实现: css样式: /*** @date 2021/1/20 16:10*//* 取消默认间距 */* {margin: 0; ...

  5. HTML+CSS+JS实现 ❤️3D网状球体动画特效❤️

    效果演示: 代码目录: 主要代码实现: CSS样式: @property --color-position {syntax: '<length-percentage>';inherits: ...

  6. js进阶 13-5 jquery队列动画如何实现

    js进阶 13-5 jquery队列动画如何实现 一.总结 一句话总结:同一个jquery对象,直接写多个animate()就好. 1.什么是队列动画? 比如说先左再下,而不是左下一起走 2.怎么实现 ...

  7. php加入js动态效果,js怎么给输入框增加动画效果

    这次给大家带来js怎么给输入框增加动画效果,js给输入框增加动画效果的注意事项有哪些,下面就是实战案例,一起来看一下. (function() { function p() { window.requ ...

  8. HTML设置页面动画效果有几种,前端制作动画的几种方式(css3,js)

    制作动态的网页是是前端工程师必备的技能,很好的实现动画能够极大的提高用户体验,增强交互效果,那么动画有多少实现方式,一直对此有选择恐惧症的我就总结一下,以便在开发的时候选择最好的实现方式. 1.css ...

  9. svg+js鼠标悬停卡片充满动画js特效

    下载地址svg+js的鼠标悬停动画特效,css不规则的图形鼠标悬停后卡片充满动画特效. dd:

最新文章

  1. Skype for Business Server 2015-12-WAP-发布-2-邮件服务器
  2. getRunningTask API
  3. STM32F103CB 芯片FLASH DOWNLOAD编程地址范围设置相关问题记录
  4. 阿里妈妈品牌广告价值建模
  5. mc有什么红石机器人_我的世界10月考试!来测测你的MC成绩吧~
  6. 【华为云技术分享】程序员真香定律:源码即设计
  7. java零碎要点010---Java实现office文档与pdf文档的在线预览功能
  8. tile布局的ButtonBar
  9. mybatis generator自动生成sqlmap代码的不完善之处以及解决方法
  10. qzone.class.php,PHP QQ登录接口应用_PHP教程 - str_repeat
  11. workbench字符匹配错误_猪憨憨刷题笔记-LeetCode-10 正则表达式匹配
  12. matlab 快速傅里叶变换函数(fft)编写
  13. cad边长提取lisp_用lisp怎么提取cad中文字-内容-*通用符匹配(值 :设定)生成excel文件...
  14. 零基础学习 iOS 开发?如何系统学习 iOS ?
  15. Mapped Statements collection already contains value
  16. 情人节浪漫3D照片墙【附源码】
  17. MIUI12或android11找不到QQ文件的问题
  18. 一个男孩子如果到了23岁,就不会再长高了。。。
  19. 数据增强系列(2)如何使用Augly库进行数据增强
  20. 为什么说用PHP开发大型系统令人不爽

热门文章

  1. Python+Vue计算机毕业设计BeatHouse伴奏交易平台z19pu(源码+程序+LW+部署)
  2. 【3D建模工具】上海道宁与McNeel为您提供强大的专业3D造型软件
  3. 为网站配置免费的HTTPS证书 2-4
  4. 507 Lusir的游戏 二分 数论 [代码源][namomo spring camp]每日一题div2
  5. 【WC2013】糖果公园 树上莫队
  6. 蓝牙宠物食物称重碗方案开发
  7. 四轮 控制算法 麦轮_AGV-麦克纳姆轮小车控制总结
  8. 腾讯云企业邮箱怎么样?
  9. 【微信小程序】WXML WXSS JS
  10. 厉害了!自己动手也能做一个推荐系统!