Evert
Evert

Reputation: 99533

Approach with <canvas> for a large 'map'

I'm looking to build a tile-based javascript game that has a top-down view. Think of: Sim City Classic.

I'm wondering what the right approach is for a map that's larger than the users' viewport. Should I create a large canvas for the entire map and let the user use the browser-scroll, or should I make the canvas the size of the browser, and manually implement scrolling.

In both cases I can see that there might be performance considerations. The big map is a big canvas which can be slow, and for the small one I will need to manually scroll (and redraw a lot during scrolling?)

Upvotes: 3

Views: 2150

Answers (1)

Blindman67
Blindman67

Reputation: 54026

Best approach for maps is to keep an offscreen canvas that is slightly larger than the display. Render the map onto that and render that canvas onto the display canvas. While there is no movement you don't need to update the map, when there are only small pixel movements you only need to rerender new stuff in the direction of movement. This is done by copying what is already rendered and moving it in the opposite direction of movement and then just rendering what is new along the two edges in the direction of travel. If zooming in you can just zoom the background map and re render it in parts, rather than in one go. Same for zooming out. Just render the edges, and then re render the map in parts.

Look at google maps. This is how they do it. Of Course your mapping images will not have to wait for them to come from the server so the user will not see blank areas while the map waits for content.

This method is the best way to handle large regular and irregular tiled maps.

If the map is animated then you will just have to brute force it and rerender the map each animation frame, but still use the off screen canvas. It may pay to reduce the maps animation rate to half the frame rate. That way you can interlace the animations, spreading the half the animations to every odd frame and the other half to even.

Upvotes: 3

Related Questions