Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D side scrolling camera view in html5

I was wondering how I could go about making a camera-like view where I could scroll a level within a canvas element just like this:

http://playbiolab.com/

Biolab screenshot

like image 545
Oni Enzeru Avatar asked Oct 26 '11 22:10

Oni Enzeru


2 Answers

So you want a 500x500 canvas to display something (a game level) that is really 9000x500 or so.

This is fine. What you do is think of the canvas as a "viewport" for a larger scene. You translate the canvas (or everything else) to the appropriate spot and draw all of the relevant things at that spot.

Here's an example:

http://jsfiddle.net/hKrrY/

Click on the canvas and hold down your left arrow key to see the scene go by while the red player dot stays "still".

As you scroll by the 100x100 canvas, you are seeing objects that are being drawn at once-offscreen locations like (330,50). Translating the canvas brings them into view.


I guess its worth mentioning that this is where making optimizations in a canvas starts to really matter. The example I gave above is a very simplistic way to make a viewport, and as your code progresses you're going to want to think more and more about what it is you're drawing and how much you're drawing. You'll want to avoid drawing objects that are completely offscreen, for instance, and if your game or app has a background that is 9000x500 you probably don't want to be drawing the entire thing every time!

So the concept is the takeaway here, but you'll want to think very hard about how you implement it and how much work you are making the canvas do. If you end up with performance problems in your side-scrolling app, be sure to let us know :)

like image 155
Simon Sarris Avatar answered Oct 19 '22 04:10

Simon Sarris


I've always found it's more efficient to wrap your canvas in a div with the width and height of your viewport and the overflow set to hidden then just draw your whole canvas and scroll the div to where you where you want to view.

So the html would be:

<div id='wrapper' style='width: 200px; height: 200px; overflow: hidden;'>
     <canvas width='1000' height='1000'></canvas>
</div>

and the javascript would be something like

function scrollWrapper(x, y){
    var wrapper = document.getElementById('wrapper');  
    wrapper.scrollTop = x;
    wrapper.scrollLeft = y;
}

Then just call the function with the x and y you want to view. you could wrap it in a setTimeout or something if you wanted to move there instead of just jumping there.

like image 23
hobberwickey Avatar answered Oct 19 '22 02:10

hobberwickey