Besides creating HTML buttons on top of the canvas, we can make those buttons
interact directly with engine objects.
For this we use the sendMessage function, which invokes a method
inside an object's script.
// ========================
// HTML Button with sendMessage
// ========================
/* global canvas, sendMessage */
function Start(obj) {
obj._htmlButton = document.createElement("button");
obj._htmlButton.innerText = "Heal Player";
obj._htmlButton.style.position = "absolute";
obj._htmlButton.style.zIndex = 1000;
obj._htmlButton.style.padding = "8px 14px";
obj._htmlButton.style.borderRadius = "6px";
obj._htmlButton.style.background = "#28a745";
obj._htmlButton.style.color = "white";
obj._htmlButton.style.cursor = "pointer";
// When clicked, send message to "Player"
obj._htmlButton.onclick = () => {
sendMessage("Player", "Heal", 50);
// 👆 calls Player.Heal(50) if the script contains that function
};
document.body.appendChild(obj._htmlButton);
}
function Update(obj, dt) {
if (!obj._htmlButton) return;
const rect = canvas.getBoundingClientRect();
const w = 120;
const h = 40;
// Position bottom-right relative to the canvas
obj._htmlButton.style.left = rect.right - w - 20 + "px";
obj._htmlButton.style.top = rect.bottom - h - 20 + "px";
obj._htmlButton.style.width = w + "px";
obj._htmlButton.style.height = h + "px";
}
function OnDestroy(obj) {
if (obj._htmlButton) {
obj._htmlButton.remove();
obj._htmlButton = null;
}
}
HTMLSendMessage.js in your scripts folder.Player object has a script with this function:
function Heal(obj, amount) {
obj.hp += amount;
console.log(obj.name + " healed +" + amount);
}
Player.Heal(50) will be executed.sendMessage you can call any method defined in your object's scripts.
This allows you to use HTML buttons as menus, HUDs, or debug panels.