HTML 5 canvas performance

I just started playing with canvas with an HTML5 object. For the sake of performance tests, I made a little ping pong game .

Are there any performance improvements that I could use?

The ball appears blue with a touch of red, but my declaration should be yellow. How can i fix this?

+4
source share
1 answer

This should help you with the color of the ball;

function drawBall (x, y, r) { ctx.beginPath(); ctx.fillStyle = "yellow"; ctx.arc(x, y, r, 0, Math.PI*2, false); ctx.closePath(); ctx.fill(); //added fps++; } function drawP1 (h) { ctx.fillStyle = '#FF0000'; ctx.fillRect(0, h, 20, 100); //ctx.fill(); // remove in P2 also fps++; return true; }; 

fill () does not apply to fillRect (), the latter draws a filled rectangle, and fill () - to fill patches.

Not so much that you can improve with a simple pong game, but I will give some general tips on canvas performance:

  • FillStyle / strokeStyle notes are expensive, avoiding color switching.
  • drawing complex shapes is also expensive. you can draw then and use the pixel api to render
  • try to keep the separation of rendering and processing, this will give you room for improvement.
  • try using pure js for games / animations with high FPS

As said, very general advice and may not be suitable for each case.

+4
source

Source: https://habr.com/ru/post/1307266/


All Articles