在使用 Canvas API 前,必須檢測瀏覽器是否支持。本文介紹三種檢測方案:直接檢測、動態創建檢測、Modernizr 庫檢測,分析優缺點並給出生產環境推薦做法。
const canvas = document.getElementById('myCanvas');
if (!canvas || !canvas.getContext) {
// 不支持 Canvas 或元素不存在
showFallbackContent();
return;
}
const ctx = canvas.getContext('2d');
// 繼續繪圖邏輯...
getElementById 返回 null)getContext 方法是否存在
function isCanvasSupported() {
const canvas = document.createElement('canvas');
return !!(canvas.getContext && canvas.getContext('2d'));
}
// 使用
if (!isCanvasSupported()) {
document.body.innerHTML = '您的瀏覽器不支持 Canvas,請升級瀏覽器。
';
return;
}
// 正常初始化 Canvas 應用...
<canvas> 標籤canvas.getContext('webgl') || canvas.getContext('experimental-webgl')
<script src="modernizr-custom.js"></script>
<script>
if (!Modernizr.canvas) {
// 不支持 Canvas
loadPolyfillOrFallback();
return;
}
// 支持 Canvas
initCanvasApp();
</script>
<html class="canvas canvastext no-webgl ...">,CSS 可直接針對降級樣式
// CSS 中針對無 Canvas 降級
.no-canvas .chart-container {
background: url(static-chart.png) center/contain no-repeat;
}
// JS 中條件加載 Polyfill
Modernizr.load({
test: Modernizr.canvas,
nope: ['excanvas.js', 'canvas-polyfill.css'], // IE8- 用 excanvas 模擬
complete: () => initApp()
});
// 檢測具體上下文類型
Modernizr.canvas // 2D context
Modernizr.webgl // WebGL 1
Modernizr.webgl2 // WebGL 2
Modernizr.offscreencanvas // OffscreenCanvas
| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 簡單頁面、單一 Canvas 應用 | 方法二(動態創建) | 零依賴、代碼簡潔、足夠可靠 |
| 需檢測多項 HTML5/CSS3 特性 | Modernizr 定製構建 | 統一特性檢測入口、CSS 類名掛鉤、條件加載 |
| 需支持 IE8/舊瀏覽器 | Modernizr + excanvas/excanvas.js | 統一 Polyfill 加載邏輯 |
| 現代項目(只支持現代瀏覽器) | 方法二 + 可選 canvas.getContext('2d', {willReadFrequently: true}) | 原生 API、無額外依賴、性能最優 |
const ctx = canvas.getContext('2d');
// 檢測特定方法是否存在
const hasPath2D = typeof Path2D !== 'undefined';
const hasRoundRect = typeof ctx.roundRect === 'function';
const hasEllipse = typeof ctx.ellipse === 'function';
const hasImageSmoothing = 'imageSmoothingEnabled' in ctx;
// 檢測屬性支持
const supportsLineDash = 'setLineDash' in ctx;
const supportsConicGradient = CSS.supports('background', 'conic-gradient(red, blue)');
<canvas>內容</canvas> 內放 <img src="fallback.png"> 或文字說明excanvas (IE8- VML 模擬)、canvas-polyfill (部分 API 模擬)Canvas 支持檢測是應用健壯性的第一道防線。現代項目中,動態創建檢測法足以應對 99% 場景;大型項目引入 Modernizr 定製版 統一管理特性檢測與 Polyfill 加載。切記:特性檢測優於瀏覽器嗅探,始終檢測能力而非身份。