且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

html5中的2D侧滚动相机视图

更新时间:2022-10-16 12:50:26

所以你想要一个 500x500 的画布来显示实际上是 9000x500 左右的东西(游戏关卡).

这很好.您所做的是将画布视为更大场景的视口".您将画布(或其他所有内容)翻译到适当的位置并在该位置绘制所有相关的东西.

这是一个例子:

http://jsfiddle.net/hKrrY/

单击画布并按住左箭头键可查看场景经过,而红色播放器点保持静止".

当您在 100x100 画布上滚动时,您会看到在 (330,50) 等离屏位置绘制的对象.平移画布会将它们带入视野.

我想值得一提的是,这就是在画布中进行优化开始真正重要的地方.我在上面给出的示例是制作视口的一种非常简单的方法,随着代码的进展,您将越来越想考虑您正在绘制什么以及您正在绘制多少.例如,您需要避免绘制完全在屏幕外的对象,如果您的游戏或应用的背景为 9000x500,您可能不想每次都绘制整个对象!

所以这个概念是这里的要点,但是您需要非常认真地思考如何实现它以及您在画布上做了多少工作.如果您最终在横向滚动应用中遇到性能问题,请务必告知我们 :)

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/

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 :)