你必须知道的10个提高Canvas性能技巧
你还在抱怨自己写的canvas demo徘徊在10帧以下吗?你还在烦恼打开自己写的应用就听见CUP风扇转吗?你正在写一个javascript Canvas库吗?那么下面九点就是你必须知道的! 一.预渲染 错误代码: var canvas = document.getElementById( "myCanvas" ); var cont
你还在抱怨自己写的canvas demo徘徊在10帧以下吗?你还在烦恼打开自己写的应用就听见CUP风扇转吗?你正在写一个javascript Canvas库吗?那么下面九点就是你必须知道的!
一.预渲染
错误代码:
<span>var </span><span>canvas = document.getElementById(</span><span>"myCanvas"</span><span>); </span><span>var </span><span>context = </span><span>this</span><span>.canvas.getContext(</span><span>'2d'</span><span>); </span><span>var </span><span>drawAsync = eval(Jscex.compile(</span><span>"async"</span><span>, </span><span>function </span><span>() { </span><span>while </span><span>(</span><span>true</span><span>) { drawMario(context); $await(Jscex.Async.sleep(</span><span>1000</span><span>)); } })) drawAsync().start(); </span>
正确代码:
<span>var </span><span>canvas = document.getElementById(</span><span>"myCanvas"</span><span>); </span><span>var </span><span>context = </span><span>this</span><span>.canvas.getContext(</span><span>'2d'</span><span>); </span><span>var </span><span>m_canvas = document.createElement(</span><span>'canvas'</span><span>); </span><span>m_canvas.width = </span><span>64</span><span>; m_canvas.height = </span><span>64</span><span>; </span><span>var </span><span>m_context = m_canvas.getContext(</span><span>'2d'</span><span>); drawMario(m_context); </span><span>var </span><span>drawAsync = eval(Jscex.compile(</span><span>"async"</span><span>, </span><span>function </span><span>() { </span><span>while </span><span>(</span><span>true</span><span>) { context.drawImage(m_canvas, </span><span>0</span><span>, </span><span>0</span><span>); $await(Jscex.Async.sleep(</span><span>1000</span><span>)); } })) drawAsync().start(); </span>
这里m_canvas的宽度和高度控制得越小越好。
二.尽量少调用canvasAPI
错误代码:
<span>for </span><span>(</span><span>var </span><span>i = </span><span>0</span><span>; i <span>1</span><span>; i++) { </span><span>var </span><span>p1 = points[i]; </span><span>var </span><span>p2 = points[i + </span><span>1</span><span>]; context.beginPath(); context.moveTo(p1.x, p1.y); context.lineTo(p2.x, p2.y); context.stroke(); } </span></span>
正确代码:
<span>context.beginPath(); </span><span>for </span><span>(</span><span>var </span><span>i = </span><span>0</span><span>; i <span>1</span><span>; i++) { </span><span>var </span><span>p1 = points[i]; </span><span>var </span><span>p2 = points[i + </span><span>1</span><span>]; context.moveTo(p1.x, p1.y); context.lineTo(p2.x, p2.y); } context.stroke(); </span></span>
三.尽量少改变CANVAS状态
错误代码:
<span>for </span><span>(</span><span>var </span><span>i = </span><span>0</span><span>; i <span>2 </span><span>? COLOR1 : COLOR2); context.fillRect(i * GAP, </span><span>0</span><span>, GAP, </span><span>480</span><span>); } </span></span>
正确代码:
<span>context.fillStyle = COLOR1; </span><span>for </span><span>(</span><span>var </span><span>i = </span><span>0</span><span>; i <span>2</span><span>; i++) { context.fillRect((i * </span><span>2</span><span>) * GAP, </span><span>0</span><span>, GAP, </span><span>480</span><span>); } context.fillStyle = COLOR2; </span><span>for </span><span>(</span><span>var </span><span>i = </span><span>0</span><span>; i <span>2</span><span>; i++) { context.fillRect((i * </span><span>2 </span><span>+ </span><span>1</span><span>) * GAP, </span><span>0</span><span>, GAP, </span><span>480</span><span>); } </span></span></span>
四.重新渲染的范围尽量小
错误代码:
<span>context.fillRect(</span><span>0</span><span>, </span><span>0</span><span>, canvas.width, canvas.height); </span>
正确代码:
<span>context.fillRect(</span><span>20</span><span>, </span><span>20</span><span>, </span><span>100</span><span>, </span><span>100</span><span>); </span>
五.复杂场景使用多层画布
<span><span>canvas </span><span>width=</span><span>"600" </span><span>height=</span><span>"400" </span><span>style=</span><span>"</span><span>position</span><span>: absolute; </span><span>z-index</span><span>: 0"</span><span>> </span><span>canvas</span><span>> <span>canvas </span><span>width=</span><span>"600" </span><span>height=</span><span>"400" </span><span>style=</span><span>"</span><span>position</span><span>: absolute; </span><span>z-index</span><span>: 1"</span><span>> </span><span>canvas</span><span>> </span></span></span>
六.不要使用阴影
<span>context.shadowOffsetX = </span><span>5</span><span>; context.shadowOffsetY = </span><span>5</span><span>; context.shadowBlur = </span><span>4</span><span>; context.shadowColor = </span><span>'rgba(255, 0, 0, 0.5)'</span><span>; context.fillRect(</span><span>20</span><span>, </span><span>20</span><span>, </span><span>150</span><span>, </span><span>100</span><span>); </span>
七.清除画布
详细性能差别:
http://simonsarris.com/blog/346-how-you-clear-your-canvas-matters
一般情况下:clearRect的性能优于fillRect优于canvas.width = canvas.width;
八.像素级别操作尽量用整数
几种取整数的方法:
<span>rounded = (</span><span>0.5 </span><span>+ somenum) | </span><span>0</span><span>; </span><span>rounded = ~ ~(</span><span>0.5 </span><span>+ somenum); </span><span>rounded = (</span><span>0.5 </span><span>+ somenum) <span>0</span><span>; </span></span>
九.使用requestAnimationFrame制作游戏或动画
<p></p><p> (<span>function</span> () {<br> <span>var</span> lastTime = 0;<br> <span>var</span> vendors = ['ms', 'moz', 'webkit', 'o'];<br> <span>for</span> (<span>var</span> x = 0; x window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];<br> window.cancelAnimationFrame =<br> window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];<br> }<br><br> <span>if</span> (!window.requestAnimationFrame)<br> window.requestAnimationFrame = <span>function</span> (callback, element) {<br> <span>var</span> currTime = <span>new</span> Date().getTime();<br> <span>var</span> timeToCall = Math.max(0, 16 - (currTime - lastTime));<br> <span>var</span> id = window.setTimeout(<span>function</span> () { callback(currTime + timeToCall); },<br> timeToCall);<br> lastTime = currTime + timeToCall;<br> <span>return</span> id;<br> };<br><br> <span>if</span> (!window.cancelAnimationFrame)<br> window.cancelAnimationFrame = <span>function</span> (id) {<br> clearTimeout(id);<br> };<br> } ());</p>
十.其他
与渲染无关的计算交给worker
复杂的计算交给引擎(自己写,或者用开源的),比如3D、物理
缓存load好的图片,canvas上画canvas,而不是画image
同步
本文已同步更新至:
HTML5实验室【目录】: http://www.cnblogs.com/iamzhanglei/archive/2011/11/06/2237870.html

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Ollama is a super practical tool that allows you to easily run open source models such as Llama2, Mistral, and Gemma locally. In this article, I will introduce how to use Ollama to vectorize text. If you have not installed Ollama locally, you can read this article. In this article we will use the nomic-embed-text[2] model. It is a text encoder that outperforms OpenAI text-embedding-ada-002 and text-embedding-3-small on short context and long context tasks. Start the nomic-embed-text service when you have successfully installed o

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values takes a relatively long time.

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

Performance comparison of different Java frameworks: REST API request processing: Vert.x is the best, with a request rate of 2 times SpringBoot and 3 times Dropwizard. Database query: SpringBoot's HibernateORM is better than Vert.x and Dropwizard's ORM. Caching operations: Vert.x's Hazelcast client is superior to SpringBoot and Dropwizard's caching mechanisms. Suitable framework: Choose according to application requirements. Vert.x is suitable for high-performance web services, SpringBoot is suitable for data-intensive applications, and Dropwizard is suitable for microservice architecture.

The impact of functions on C++ program performance includes function call overhead, local variable and object allocation overhead: Function call overhead: including stack frame allocation, parameter transfer and control transfer, which has a significant impact on small functions. Local variable and object allocation overhead: A large number of local variable or object creation and destruction can cause stack overflow and performance degradation.

Effective techniques for optimizing C++ multi-threaded performance include limiting the number of threads to avoid resource contention. Use lightweight mutex locks to reduce contention. Optimize the scope of the lock and minimize the waiting time. Use lock-free data structures to improve concurrency. Avoid busy waiting and notify threads of resource availability through events.

In PHP, the conversion of arrays to objects will have an impact on performance, mainly affected by factors such as array size, complexity, object class, etc. To optimize performance, consider using custom iterators, avoiding unnecessary conversions, batch converting arrays, and other techniques.

In Go language program development, function reconstruction skills are a very important part. By optimizing and refactoring functions, you can not only improve code quality and maintainability, but also improve program performance and readability. This article will delve into the function reconstruction techniques in the Go language, combined with specific code examples, to help readers better understand and apply these techniques. 1. Code example 1: Extract duplicate code fragments. In actual development, we often encounter reused code fragments. At this time, we can consider extracting the repeated code as an independent function to
