10 Canvas improvement skills you must know

Source: Internet
Author: User
Are you still complaining that your canvasdemo is hovering below 10 frames? Are you still worried about opening your own applications and you will hear the transfer of the CUP fan? Are you writing a javascriptCanvas library? You must know the following nine points! I. Pre-rendering error code: varcanvasdocument. getElementById (myCanvas); varcont

Are you still complaining that your canvas demo is hovering below 10 frames? Are you still worried about opening your own applications and you will hear the transfer of the CUP fan? Are you writing a javascript Canvas library? You must know the following nine points! I. Pre-rendering error code: var canvas = document. getElementById ("myCanvas"); var cont

Are you still complaining that your canvas demo is hovering below 10 frames? Are you still worried about opening your own applications and you will hear the transfer of the CUP fan? Are you writing a javascript Canvas library? You must know the following nine points!

I. Pre-rendering

Error code:

      var canvas = document.getElementById("myCanvas");      var context = this.canvas.getContext('2d');      var drawAsync = eval(Jscex.compile("async", function () {          while (true) {              drawMario(context);              $await(Jscex.Async.sleep(1000));          }      }))      drawAsync().start();

Correct code:

      var canvas = document.getElementById("myCanvas");      var context = this.canvas.getContext('2d');      var m_canvas = document.createElement('canvas');m_canvas.width = 64;      m_canvas.height = 64;      var m_context = m_canvas.getContext('2d');      drawMario(m_context);      var drawAsync = eval(Jscex.compile("async", function () {          while (true) {              context.drawImage(m_canvas, 0, 0);              $await(Jscex.Async.sleep(1000));          }      }))      drawAsync().start();

Here, the smaller the width and height of m_canvas, the better.

Ii. Try to call canvasAPI as few as possible

Error code:

       for (var i = 0; i < points.length - 1; i++) {          var p1 = points[i];          var p2 = points[i + 1];          context.beginPath();          context.moveTo(p1.x, p1.y);          context.lineTo(p2.x, p2.y);          context.stroke();      } 

Correct code:

      context.beginPath();      for (var i = 0; i < points.length - 1; i++) {          var p1 = points[i];          var p2 = points[i + 1];          context.moveTo(p1.x, p1.y);          context.lineTo(p2.x, p2.y);      }      context.stroke();
3. Minimize CANVAS status changes

Error code:

      for (var i = 0; i < STRIPES; i++) {          context.fillStyle = (i % 2 ? COLOR1 : COLOR2);          context.fillRect(i * GAP, 0, GAP, 480);      } 

Correct code:

      context.fillStyle = COLOR1;      for (var i = 0; i < STRIPES / 2; i++) {          context.fillRect((i * 2) * GAP, 0, GAP, 480);      }      context.fillStyle = COLOR2;      for (var i = 0; i < STRIPES / 2; i++) {          context.fillRect((i * 2 + 1) * GAP, 0, GAP, 480);      }
4. The scope of re-rendering should be as small as possible

Error code:

  context.fillRect(0, 0, canvas.width, canvas.height); 

Correct code:

      context.fillRect(20, 20, 100, 100);
5. Use multi-layer canvas in complex scenarios
 
 
 
6. Do not use shadow.
      context.shadowOffsetX = 5;      context.shadowOffsetY = 5;      context.shadowBlur = 4;      context.shadowColor = 'rgba(255, 0, 0, 0.5)';      context.fillRect(20, 20, 150, 100);
7. Clear the canvas

Detailed performance differences:
Http://simonsarris.com/blog/346-how-you-clear-your-canvas-matters
AverageIn this case, clearRect has better performance than fillRect and canvas. width = canvas. width;

8. Try to use integers for Pixel-level operations

Several methods to take integers:

rounded = (0.5 + somenum) | 0;rounded = ~ ~(0.5 + somenum);rounded = (0.5 + somenum) << 0;
9. Use requestAnimationFrame to create a game or animation

(function () {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}

if (!window.requestAnimationFrame)
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};

if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
} ());

10. Others

Computing unrelated to rendering is handed over to worker

Complex computing is handed over to the engine (self-written or open-source), such as 3D and physical

Cache the loaded image. Draw a canvas on the canvas instead of an image.

Synchronization

This article has been synchronously updated:

HTML5 lab [Directory]: http://www.cnblogs.com/iamzhanglei/archive/2011/11/06/2237870.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.