<!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Canvas 动画优化</title>
   <style>
     canvas {
       height: 300px;
       width: 500px;
       border: 1px solid black;
     }
   </style>
 </head>
 <body>
   <canvas width="500px" height="300px"></canvas>
   <script>
     let canvas = document.querySelector("canvas");
     let ctx = canvas.getContext('2d');
     let height = 300;
     let width = 500;
     let offset = 0;
     let num = 0;
     
     function draw() {
       ctx.clearRect(0, 0, width, height);
       ctx.beginPath();
       
       // ctx.fillStyle = '#abcdef';
       ctx.moveTo(0 + offset - 500, height / 2);
       ctx.quadraticCurveTo(width / 4 + offset - 500, height / 2 - 100 * Math.sin(num), width / 2 + offset - 500, height / 2);
       ctx.quadraticCurveTo(width / 4 * 3 + offset - 500, height / 2 + 100 * Math.sin(num), width + offset - 500, height / 2);
       
       ctx.moveTo(0 + offset, height / 2);
       ctx.quadraticCurveTo(width / 4 + offset, height / 2 - 100 * Math.sin(num), width / 2 + offset, height / 2);
       ctx.quadraticCurveTo(width / 4 * 3 + offset, height / 2 + 100 * Math.sin(num), width + offset, height / 2);
       // ctx.fill()
       ctx.stroke();
       offset += 5;
       offset %= 500;
       num = 0.3;
     }
     
     function animate() {
       draw();
       requestAnimationFrame(animate);
     }
     
     animate();
 
   </script>
 </body>
 </html>
<p>可以对它进行优化,主要有以下几点:</p>
<ol>
<li>
<p>尽量减少 DOM 操作,可以将 canvas 元素和上下文对象的获取放在一起,不需要每次都获取。</p>
</li>
<li>
<p>尽量减少重绘区域的大小,可以只清除需要重绘的部分,而不是整个画布。</p>
</li>
<li>
<p>可以使用 requestAnimationFrame 替代 setInterval,这样可以更加流畅地进行动画渲染。</p>
</li>
</ol>
<p>优化前后的差别:</p>
<p>优化前的代码可能存在性能问题,每次都需要重绘整个画布,而且使用了 setInterval,可能会导致帧率不稳定。优化后的代码可以减少重绘区域大小,使用 requestAnimationFrame 来进行动画渲染,代码更加简洁,性能更好,能够更加流畅地进行动画渲染。</p>
Canvas 动画优化技巧:减少 DOM 操作、重绘区域和使用 requestAnimationFrame

原文地址: https://www.cveoy.top/t/topic/lLSH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录