如何在窗口大小调整时动态修改Kaboom游戏的画布尺寸
解决方案
Kaboom 初始化返回的上下文实例自带resize()方法,你之前直接修改 canvas 无效是因为 Kaboom 内部维护了独立的坐标系统和宽高缓存,原生修改 canvas 尺寸不会同步更新内部状态,width()、height()等内置方法还是会返回旧的尺寸值。
你只需要调整两处代码即可实现响应式尺寸调整:
- 存储 Kaboom 初始化返回的上下文实例
- 窗口 resize 时先调用上下文的
resize()方法更新内部状态,再调整元素位置尺寸
修改后的完整代码
// 存储kaboom上下文实例 const k = kaboom(); function makeWallComps(name, x, y, w, h) { return [ name, "wall", k.origin("center"), k.rect(w, h), k.pos(x, y), k.outline(), k.area() ]; } let leftWall = k.add(makeWallComps("left", 5, k.height() / 2, 10, k.height())); let rightWall = k.add(makeWallComps("right", k.width() - 5, k.height() / 2, 10, k.height())); let topWall = k.add(makeWallComps("top", k.width() / 2, 5, k.width() - 20, 10)); let bottomWall = k.add(makeWallComps("bottom", k.width() / 2, k.height() - 5, k.width() - 20, 10)); let obj = k.add([ "obj", k.origin("center"), k.rect(20, 20), k.pos(k.width() / 2, k.height() / 2), k.outline(), k.area(), { dir: k.rand(-180, 180) } ]); obj.use(k.move(obj.dir, 100)); // 碰撞反弹逻辑 obj.collides("wall", function huh(obstacle) { if (obstacle.is("left")) { console.log("left"); if (obj.dir < -90) { obj.dir = -180 - obj.dir; } else if (obj.dir > 90) { obj.dir = 180 - obj.dir; } } else if (obstacle.is("right")) { console.log("right"); if (obj.dir < 0) { obj.dir = -180 - obj.dir; } else { obj.dir = 180 - obj.dir; } } else if (obstacle.is("top") || obstacle.is("bottom")) { obj.dir *= -1; } obj.use(k.move(obj.dir, 100)); }); window.addEventListener( 'resize', () => { const newWidth = document.documentElement.clientWidth; const newHeight = document.documentElement.clientHeight; // 调用内置resize方法同步更新画布和内部状态 k.resize(newWidth, newHeight); leftWall.use(k.pos(5, k.height() / 2)); leftWall.use(k.rect(10, k.height())); rightWall.use(k.pos(k.width() - 5, k.height() / 2)); rightWall.use(k.rect(10, k.height())); topWall.use(k.pos(k.width() / 2, 5)); topWall.use(k.rect(k.width() - 20, 10)); bottomWall.use(k.pos(k.width() / 2, k.height() - 5)); bottomWall.use(k.rect(k.width() - 20, 10)); } );
<script src="https://cdn.jsdelivr.net/npm/kaboom@2000.0.0-beta.24/dist/kaboom.min.js"></script>
内容的提问来源于stack exchange,提问作者Paul Wheeler
相关产品推荐
相关产品推荐

