References

Beginner-friendly references for web development, with live, editable examples.

The HTML oncontextlost event

Event Updated
Quick answer

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 inline oncontextlost attribute — 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?
It runs JavaScript when a canvas context is lost. In JavaScript the event is named contextlost.
Why would a canvas context be lost?
The browser can drop the GPU-backed context after a driver reset or under memory pressure; your app should handle it and recover.
How do I recover from a lost canvas context?
Listen for contextrestored, then re-create resources and redraw.
Should I use the oncontextlost attribute or addEventListener?
Prefer addEventListener('contextlost', …) in JavaScript. The inline oncontextlost attribute works but mixes behavior into the markup and allows only one handler per element.