CKTIS / HTML
oncontextrestored — handling canvas context restoration
The oncontextrestored attribute specifies code for handling the contextrestored event. For a canvas with a 2D context, the event signals restoration after context loss; the application should then rebuild its drawing settings and content.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
<canvas oncontextrestored="/* JavaScript using event */"></canvas>
canvas.oncontextrestored = (event) => { /* handle restoration */ };
canvas.addEventListener("contextrestored", handler);oncontextrestored is an HTML event-handler attribute and a corresponding JavaScript property from GlobalEventHandlers. The event name is contextrestored, without the on prefix. In HTML, the attribute value is JavaScript code with an available event parameter; the JavaScript property accepts a function or null. addEventListener("contextrestored", handler) is an alternative that allows multiple listeners.
The browser dispatches this event to the canvas after successfully restoring a lost 2D context. Context loss resets the drawing state, so the handler should reapply necessary styles and transforms and redraw the scene from application data. Do not assume that previous pixels are recovered automatically. Assigning a handler does not itself restore the context or guarantee that restoration will succeed.
The example tests only attribute wiring by dispatching a synthetic event. Its event.isTrusted value is false; this does not test actual context loss or recovery. Run it in a browser supporting the property, with inline scripting allowed.
Examples
<!doctype html>
<meta charset="utf-8">
<title>oncontextrestored test</title>
<canvas id="surface" width="80" height="40"
oncontextrestored="console.log(event.type, event.isTrusted)"></canvas>
<script>
const canvas = document.getElementById("surface");
if (!("oncontextrestored" in canvas)) {
throw new Error("oncontextrestored is not supported");
}
canvas.dispatchEvent(new Event("contextrestored"));
</script>Result
contextrestored false
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.