References

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

The HTML oncontextrestored event

Event Updated
Quick answer

The HTML oncontextrestored attribute runs JavaScript when a lost canvas rendering context is restored. It is an inline handler for the contextrestored event; in modern code prefer addEventListener('contextrestored', …).

Overview

The oncontextrestored event attribute runs JavaScript when a canvas context is restored. In JavaScript the event itself is named contextrestored — 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 oncontextrestored HTML attribute, but the modern, recommended approach is element.addEventListener('contextrestored', 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 oncontextrestored="handler()">…</element>

element.addEventListener('contextrestored', handler);

Best practices

  • Prefer element.addEventListener('contextrestored', handler) over the inline oncontextrestored 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 oncontextrestored event?
It runs JavaScript when a canvas context is restored. In JavaScript the event is named contextrestored.
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 oncontextrestored attribute or addEventListener?
Prefer addEventListener('contextrestored', …) in JavaScript. The inline oncontextrestored attribute works but mixes behavior into the markup and allows only one handler per element.