The HTML oncontextlost event
The HTML oncontextlost attribute runs JavaScript when a canvas rendering context is lost. It is an inline handler for the contextlost event; in modern code prefer addEventListener('contextlost', …).
Overview
The oncontextlost event attribute runs JavaScript when a canvas context is lost. In JavaScript the event itself is named contextlost — drop the on prefix when you call addEventListener.
It relates to the <canvas> rendering context, which the browser can lose and later restore — for instance after a GPU reset or when the device is low on resources. Handling these events lets a canvas app recover gracefully instead of going blank.
You can wire this up with the inline oncontextlost HTML attribute, but the modern, recommended approach is element.addEventListener('contextlost', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element oncontextlost="handler()">…</element>
element.addEventListener('contextlost', handler);
Best practices
- Prefer
element.addEventListener('contextlost', handler)over the inlineoncontextlostattribute — it separates behavior from markup and allows multiple handlers. - Listen for context loss so a <canvas> app can pause and recover rather than break.
- Re-create textures and redraw the scene when the context is restored.
- Call
preventDefault()on the loss event to signal you will restore the context.
Frequently asked questions
What is the oncontextlost event?
contextlost.Why would a canvas context be lost?
How do I recover from a lost canvas context?
Should I use the oncontextlost attribute or addEventListener?
addEventListener('contextlost', …) in JavaScript. The inline oncontextlost attribute works but mixes behavior into the markup and allows only one handler per element.