-
Notifications
You must be signed in to change notification settings - Fork 22.4k
/
index.md
65 lines (43 loc) · 1.98 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
---
title: "HTMLCanvasElement: contextlost event"
short-title: contextlost
slug: Web/API/HTMLCanvasElement/contextlost_event
page-type: web-api-event
browser-compat: api.HTMLCanvasElement.contextlost_event
---
{{APIRef}}
The **`contextlost`** event of the [Canvas API](/en-US/docs/Web/API/Canvas_API) is fired if the user agent detects that the backing storage associated with a [`CanvasRenderingContext2D`](/en-US/docs/Web/API/CanvasRenderingContext2D) context is lost.
Contexts can be lost for several reasons like driver crashes or the application runs out of memory, etc.
By default the user agent will attempt to restore the context and then fire the [`contextrestored` event](/en-US/docs/Web/API/HTMLCanvasElement/contextrestored_event).
User code can prevent the context from being restored by calling [`Event.preventDefault()`](/en-US/docs/Web/API/Event/preventDefault) during event handling.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("contextlost", (event) => {});
oncontextlost = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Example
The code fragment below detects the `contextlost` event.
```js
const canvas = document.getElementById("canvas");
canvas.addEventListener("contextlost", (event) => {
console.log(event);
});
```
To prevent the context from being restored the code might instead look like this:
```js
const canvas = document.getElementById("canvas");
canvas.addEventListener("contextlost", (event) => {
event.preventDefault();
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`HTMLCanvasElement: contextrestored` event](/en-US/docs/Web/API/HTMLCanvasElement/contextrestored_event)
- [`CanvasRenderingContext2D.isContextLost()`](/en-US/docs/Web/API/CanvasRenderingContext2D/isContextLost)
- [`OffscreenCanvas: contextlost` event](/en-US/docs/Web/API/OffscreenCanvas/contextlost_event)