I've been messing around with HTML5 for quite some time now but this is something that I guess I haven't figured out how to handle well yet. I'm sure there's an extremely easy solution and I just haven't opened my eyes to it but anyway.
The problem is thus: I have an HTML5 canvas on which I've loaded image tiles using a function (called once on page load) which sets up an image object called
imageObj, and on
imageObj.onload, it draws the image that I want it to draw at the specific coordinates.
Now, I generally always run my main canvas game code in a
setTimeout that runs at 30 frames per second. I have a separate function which checks what keys have been pressed and stores them in an array (to account for multiple key presses), and if arrow keys are pressed, then global variables that store the player's x and y position are incremented/decremented accordingly.
Now, in the
setTimeout loop, here is where i draw a small rectangle with the x and y coordinates as that of the player x-and-y variables. However here is where I have the problem.
I do not refresh my canvas in the sense, I do not clear the screen or put a new black background covering the screen at the beginning of each frame, because then I would have to reload the tilemap and that's incredibly slow on my localhost, and would be even more so online. Furthermore, since I do not clear the screen, the rectangle of the player is leaving a trail of rectangles behind it (i.e, all previous instances of its position have a rectangle in its place)
How do I handle this? How do I manage dynamic objects over the tile map and refreshing the canvas without having to constantly reload the tile map? (or reloading the tile map in some smart way. I believe there are certain methods such as drawing the next frame beforehand or as such; I'm not too sure)
Edit: I'd rather not use any third party apis or libraries or game engines, bit of a purist that way. Also, just occurred to me, what if I had 2 canvases back to back? One with the tile map and the other containing the objects?