0
votes

I have a project I'm working on using the HTML5 canvas. I wanted to try generating a random area in a tile-based grid, each tile is drawn onto the screen in quadrants using context.drawImage() which you can imagine is quite load-heavy with a 40x22 grid. To combat this, I grab the canvas and save it as an image using canvas.toDataURL() and draw that image on each render loop.

The problem arises when I wanted to make active changes to the tile structure, in this case, drawing on the canvas to change the tiles. Each time I make a change, the background will be saved as an image again with canvas.toDataURL()so the changes are saved to the background. But this causes a massive performance dip (16fps) while constantly generating data URLs.

My question is: Is there a better way to capture the contents of a canvas to reuse which doesn't cause such a frame loss? Additionally, I don't know too much about how canvas.toDataURL() works, are the files saved to the server? Is there a bandwidth issue to using this function?

1
As a note: toDataUrl() returns you an string of the data of the image, don't use bandwidth nor saved to server, that's your task.Marcos Pérez Gude
@MarcosPérezGude Thanks, this makes sense now. I suppose converting the image into a string is what causes such a problem.Chris Bastin
Yes, if the image is too large, the string will be as big as it needs. The best way to adding performance is to reduce the loops as your posibilities, or attempt to make dataUrl() less times as loops. You can wait for a better answer, I can't help you better (you don't share code anyway). Good luck!Marcos Pérez Gude
@MarcosPérezGude Thanks for the help. So far, I've reduced strain by only saving the image when needed to, but the performance drops still when actually doing so. I will keep trying while waiting.Chris Bastin
.toDataURL is meant to serialize the canvas content for export (f.ex to the server) so don't use it to save your content between frames -- it's extremely inefficient. I must admit I don't quite understand what you are asking. If you want an efficient way to save previous canvas content while clearing & redrawing the canvas then you can create an in-memory canvas (document.createElement) and drawImage the on-screen canvas to that memory canvas. drawImage can use another canvas as its image source.markE

1 Answers

0
votes

Thanks to @markE for introducing me to the concept of creating in-memory canvases. Since I'm learning through trial and error it's understandable that I missed this method. Now my application has no frame drops and is so much more responsive.

Thanks!