Canvas support detection

A feature check lets your code decide whether it can use Canvas and what alternative to show when it cannot.

What you will learn

Feature check

const canvas = document.querySelector('#scene');
const context = canvas?.getContext('2d');

if (context) {
  context.fillRect(20, 20, 100, 60);
} else {
  document.querySelector('#fallback').hidden = false;
}
<canvas id="scene" width="160" height="100">
  A visual diagram is shown here.
</canvas>
<p id="fallback" hidden>Canvas is not available. Read the text description below.</p>

Check the capability you need at the point where you use it. A browser may support the element but still fail to provide a particular context.

Common mistakes