HTML / Canvas effect - drawImage with another canvas

I am working on a game and have some performance issues by drawing one canvas on another using drawImage. According to Chrome Profiler, I spend 60% of my time only on this drawImage call and 10% on clearRect above it ...

The source canvas is about 3000x3000 (which is quite small, I would say), and the destination canvas is 1024x768.

I thought that instead of drawing all the tiles; walls etc. etc. every loop (which gives me about 15 frames per second), which will probably be faster to draw them all once on a screen canvas, and then draw it on my main canvas, then draw entities, etc. from above, It gives me ~ 30 frames per second, but ... is this the best I'm going to get when rendering software?

My rendering cycle is basically:

ctx.clearRect(0, 0, 1024, 768); ctx.beginPath(); ctx.drawImage(map, cam.position.i, cam.position.j, 1024, 768, 0, 0, 1024, 768); ctx.closePath(); ctx.save(); ctx.translate(-cam.position.i, -cam.position.j); // draw entities, etc. ctx.restore(); 

I can’t think of what to do, except that you start using WebGL (to take advantage of its hardware acceleration) or wait until vendors implement hardware acceleration for the 2d context. I would rather not do either, so any input would be appreciated.

+4
source share
2 answers

Wow, this is a big canvas. Buffer-only storage is about 36 MB.

I will be tempted to use smaller screen tiles, for example. 1024x124 and draw visible on the main canvas. To save memory, you could only initially create visible tiles, and then generate others until they become visible. (And you can get rid or even better recycle those that are no longer visible).

I do not believe that an answer assuming you are using putImageData will give better performance, as the polling experience here indicates: why-is-putimagedata-so-slow

+2
source

Perhaps it will be faster to use getImageData for each of your "sprites" and save references to imageData arrays in your Javascript and use putImageData to render to your target canvas.

You can still render sprites using an invisible source canvas and getImageData for each of the fragments / sprites. It will use more memory, but may be faster than drawImage with source and destination canvas.

+1
source

All Articles