Consider the following simple kaboom "game":
kaboom();
function makeWallComps(name, x, y, w, h) {
return [
name,
"wall",
origin("center"),
rect(w, h),
pos(x, y),
outline(),
area()
];
}
let leftWall = add(makeWallComps("left", 5, height() / 2, 10, height()));
let rightWall = add(makeWallComps("right", width() - 5, height() / 2, 10, height()));
let topWall = add(makeWallComps("top", width() / 2, 5, width() - 20, 10));
let bottomWall = add(makeWallComps("bottom", width() / 2, height() - 5, width() - 20, 10));
let obj = add([
"obj",
origin("center"),
rect(20, 20),
pos(width() / 2, height() / 2),
outline(),
area(),
{ dir: rand(-180, 180) }
]);
obj.use(move(obj.dir, 100));
// bounce
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")) {
obj.dir *= -1;
} else if (obstacle.is("bottom")) {
obj.dir *= -1;
}
obj.use(move(obj.dir, 100));
});
window.addEventListener(
'resize',
() => {
// I want to resize the game window
// This does not work:
// canvas.width = document.documentElement.clientWidth;
// canvas.height = document.documentElement.clientHeight;
leftWall.use(pos(5, height() / 2));
leftWall.use(rect(10, height()));
rightWall.use(pos(width() - 5, height() / 2));
rightWall.use(rect(10, height()));
topWall.use(pos(width() / 2, 5));
topWall.use(rect(width() - 20, 10));
bottomWall.use(pos(width() / 2, height() - 5));
bottomWall.use(rect(width() - 20, 10));
}
);
<script src="https://cdn.jsdelivr.net/npm/kaboom@2000.0.0-beta.24/dist/kaboom.min.js"></script>
I'd like to be able to resize the canvas and have that reflected by the built in kaboom functions. Unfortunately explicitly setting the canvas dimensions doesn't work, and KaboomCtx
doesn't appear to have any resize function. Is there any way to resize a kaboom game?