oncontextlost
A 2D canvas rendering context has been lost, so drawing state may need recovery. HTML event-handler content attribute or corresponding event-handler property; the event fires only on relevant targets. The example uses document.getElementById("demo"). Event interface: Event. For the described native event: bubbles: no; cancelable: yes. A canceled event can prevent automatic restoration. WebGL uses distinct webglcontextlost events. Example: Observe a real 2D context loss or restoration; normal drawing does not trigger these events. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.
Formal Syntax & Structure
<canvas oncontextlost="handleEvent(event)"> target.addEventListener("contextlost", event => { /* handle event */ });Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| oncontextlost | JavaScript handler body | Optional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute. |
| event | Event | Event object delivered to the addEventListener callback; event.type is "contextlost". Inspect target, currentTarget, bubbles and cancelable as appropriate. |
Working Example
<canvas id="demo" width="100" height="50">Drawing preview</canvas><p role="status" id="log">Waiting for contextlost</p><script> const target = document.getElementById("demo"); const log = document.getElementById("log"); target.addEventListener("contextlost", event => { log.textContent = String(event.type); }); const ctx = target.getContext("2d"); if (ctx) ctx.fillRect(10, 10, 40, 20);</script>