Events
oncontextrestored
A lost 2D canvas context is restored. 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: no. Reinitialize drawing state and redraw; do not assume the prior bitmap survives. 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
html syntaxhtml
<canvas oncontextrestored="handleEvent(event)"> target.addEventListener("contextrestored", event => { /* handle event */ });Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| oncontextrestored | 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 "contextrestored". Inspect target, currentTarget, bubbles and cancelable as appropriate. |
Working Example
Example Snippethtml
<canvas id="demo" width="100" height="50">Drawing preview</canvas><p role="status" id="log">Waiting for contextrestored</p><script> const target = document.getElementById("demo"); const log = document.getElementById("log"); target.addEventListener("contextrestored", event => { log.textContent = String(event.type); }); const ctx = target.getContext("2d"); if (ctx) ctx.fillRect(10, 10, 40, 20);</script>