let playing = false;
const buttonControls = new AbortController();Buttons / notebook
Buttons
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
class Button extends GameObject {
size = { w: 120, h: 40 };
frame = 0;
constructor(url, ctx) {
super(url, ctx);
this.pos = { x: ctx.canvas.width / 2, y: ctx.canvas.height / 2 };
}
}class Button extends GameObject {
// …
draw() {
const columns = Math.floor(this.asset.width / this.size.w);
const { left, top } = this.hitbox;
this.ctx.drawImage(
this.asset,
(this.frame % columns) * this.size.w,
Math.floor(this.frame / columns) * this.size.h,
this.size.w,
this.size.h,
left,
top,
this.size.w,
this.size.h,
);
}
}const startButton = new Button("img/button.png", ctx);if (!playing) {
startButton.draw();
}class Button extends GameObject {
// …
containsPointer(event) {
const bounds = this.ctx.canvas.getBoundingClientRect();
const x =
((event.clientX - bounds.left) * this.ctx.canvas.width) / bounds.width;
const y =
((event.clientY - bounds.top) * this.ctx.canvas.height) / bounds.height;
const { left, right, top, bottom } = this.hitbox;
return x >= left && x <= right && y >= top && y <= bottom;
}
}function initButtonControls() {
// Add code here
}const options = { signal: buttonControls.signal };
let pressedPointer = null;function resetFrame(event) {
if (pressedPointer === null || pressedPointer === event.pointerId) {
startButton.frame = 0;
}
}
function cancelPress(event) {
if (event.pointerId === pressedPointer) {
pressedPointer = null;
resetFrame(event);
}
}canvas.addEventListener(
"pointermove",
(event) => {
if (pressedPointer !== null && pressedPointer !== event.pointerId) {
return;
}
if (startButton.containsPointer(event)) {
startButton.frame = pressedPointer === null ? 1 : 2;
} else {
resetFrame(event);
}
},
options,
);canvas.addEventListener(
"pointerdown",
(event) => {
if (
event.button !== 0 ||
pressedPointer !== null ||
!startButton.containsPointer(event)
) {
return;
}
pressedPointer = event.pointerId;
startButton.frame = 2;
canvas.setPointerCapture(event.pointerId);
},
options,
);canvas.addEventListener(
"pointerup",
(event) => {
if (event.pointerId !== pressedPointer) {
return;
}
if (startButton.containsPointer(event)) {
pressedPointer = null;
startGame();
} else {
cancelPress(event);
}
},
options,
);canvas.addEventListener("pointerleave", resetFrame, options);
canvas.addEventListener("pointercancel", cancelPress, options);
canvas.addEventListener("lostpointercapture", cancelPress, options);Promise.all(
[ball, paddle, ...bricks, startButton].map((obj) => obj.preload()),
).then(() => {
ball.pos.x = paddle.pos.x;
ball.pos.y = paddle.hitbox.top - ball.size.h / 2;
initButtonControls();
requestAnimationFrame(update);
});function startGame() {
buttonControls.abort();
ball.vel = { x: 150, y: -150 };
playing = true;
lastTimestamp = null;
}if (!playing || paddle.size.w === undefined) {
return;
}