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
- How to check for a canvas element and a 2D context
- Why feature detection is better than guessing a browser name
- How fallback text supports users and older environments
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
- Do not hide the only explanation when drawing fails.
- Do not detect a browser brand instead of detecting the feature.
- Keep the fallback useful even when Canvas works, because visual content still needs an alternative.