📌 Connecting HTML Buttons with the Engine

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.

🔧 Example: HTML button sending a message

// ========================
// 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;
  }
}

📖 How to use it

  1. Save the script as HTMLSendMessage.js in your scripts folder.
  2. Assign the script to any game object (for example, a MANAGER object).
  3. Make sure your Player object has a script with this function:
    function Heal(obj, amount) {
      obj.hp += amount;
      console.log(obj.name + " healed +" + amount);
    }
  4. When you click the HTML button, Player.Heal(50) will be executed.
💡 With 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.