根据您实际想要显示的内容,您可以将内容拆分为图块。这就是谷歌地图的工作方式,每次移动地图时,程序都会确定哪些图块在屏幕上可见并加载它们。地图上的任何标记或叠加层都会收到地图已移动的通知,并确定它们的新位置是。如果他们的位置不在屏幕上,他们可以从画布上移除。例如,Google 地图上缩放级别为 20 的所有图块的宽度为 (256 像素 * 2^20),总像素为 268,435,456。
基本上你只需要创建一个特殊的 Sprite 来跟踪它应该定位的实际 x,y 位置。每当容器移动时,您只需遍历所有子对象并确定放置它们的位置。
function onCanvasScroll() {
//determine the top left coordinates of the canvas
//you will figure out how to do this depending on how the scrolling window
//is implemented
var canvas_scroll_x;
var canvas_scroll_y;
//create a bounding box for the canvas
var view_bounds = new Rectangle(canvas_scroll_x, canvas_scroll_y, canvas.width, canvas.height);
for (child in canvas) {
var x = child.actual_x - view_bounds.x;
var y = child.actual_y - view_bounds.y;
var childBounds = new Rectangle(x, y, child.width, child.height);
//determine if the component is visible on screen
if (view_bounds.intersects(child_bounds)) {
child.visible = true;
child.x = x;
child.y = y;
}
else {
child.visible = false;
}
}
}
因此,如果您有一个位于 (100, 20000) 的画布、一个位于 (300, 20100) 的精灵和一个位于 (640,408) 的窗口,您将其放置在 (200, 100)它会在屏幕上可见。
除了将可见设置为 true 或 false 之外,更好的方法是在项目不在视图范围内时将它们从画布中完全删除。