CKTIS / HTML
oncontextlost — handling canvas context loss
The oncontextlost attribute specifies code that handles contextlost, dispatched when a canvas element's 2D rendering context is lost. It lets an application react to resource loss but does not restore the drawing itself.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
<canvas oncontextlost="handler(event)"></canvas>
canvas.oncontextlost = handler;oncontextlost is a global event handler attribute for contextlost. In practice, it is used on a canvas element whose 2D context has lost its backing storage. The attribute value is JavaScript code, not a Boolean value; the code receives the event object.
In JavaScript, you can assign a function to the canvas.oncontextlost property. Alternatively, use canvas.addEventListener('contextlost', handler). OffscreenCanvas also exposes an oncontextlost property, but it is not an HTML element and has no markup attributes. Do not confuse this event with WebGL's webglcontextlost event.
For actual context loss, the browser resets the rendering state. The contextlost event is cancelable: event.preventDefault() stops the context-restoration attempt described by the standard; do not call it if you want to allow that attempt. Restoration is not guaranteed. After contextrestored, the application should reapply the required state and redraw its content.
The example dispatches a synthetic event, so it works without causing a graphics failure. The output contextlost: false shows the event type and event.isTrusted. This tests event handling only—not resource loss or restoration.
Examples
<!doctype html>
<meta charset="utf-8">
<title>oncontextlost test</title>
<canvas id="surface" oncontextlost="document.getElementById('result').textContent = event.type + ': ' + event.isTrusted"></canvas>
<pre id="result">waiting</pre>
<script>
document.getElementById('surface').dispatchEvent(
new Event('contextlost', { cancelable: true })
);
</script>Result
contextlost: 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.