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?
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.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