SVG(Scalable Vector Graphics)是現代圖表庫(Highcharts、Chart.js、D3)的首選渲染技術。但 IE8 及以下不支援 SVG,需降級至 VML 或 Canvas。本文提供標準偵測函式與實際應用範例。
/**
* 檢查瀏覽器是否支援 SVG
* @returns {boolean}
*/
function hasSVGSupport() {
const SVG_NS = 'https://www.w3.org/2000/svg';
// 1. 檢查 document.createElementNS 是否存在
// 2. 嘗試建立 SVG 元素並檢查 createSVGRect 方法(SVG 1.1 核心功能)
return !!document.createElementNS &&
!!document.createElementNS(SVG_NS, 'svg').createSVGRect;
}
// 使用範例
if (hasSVGSupport()) {
// 初始化 Highcharts SVG 渲染
Highcharts.chart('container', { /* options */ });
} else {
// 降級:VML (IE8-) 或 Canvas 渲染
Highcharts.chart('container', { /* options */, renderer: 'VML' });
}
| 瀏覽器 | SVG 支援 | 備註 |
|---|---|---|
| Chrome 4+ | ✅ 完整 | |
| Firefox 3+ | ✅ 完整 | |
| Safari 3.2+ | ✅ 完整 | |
| Edge 12+ | ✅ 完整 | |
| IE 9-11 | ✅ 完整 | IE9 引入 SVG 支援 |
| IE 8 及以下 | ❌ 不支援 | 需 VML 降級 |
| Android Browser 4.4+ | ✅ 完整 | |
| iOS Safari 3.2+ | ✅ 完整 |
// 根據 SVG 支援動態調整圖例位置(原文提到的 x 值差異)
const legendOptions = hasSVGSupport()
? { x: -50, align: 'right' } // SVG 渲染座標系
: { x: 10, align: 'left' }; // VML 渲染座標系不同
Highcharts.chart('container', {
legend: legendOptions,
// 其他配置...
});
// 檢查 SVG Filter 支援(陰影、模糊等進階效果)
function hasSVGFilters() {
const svg = document.createElementNS('https://www.w3.org/2000/svg', 'svg');
return typeof svg.style.filter !== 'undefined' ||
typeof svg.style.webkitFilter !== 'undefined';
}
// 檢查 SMIL 動畫支援(Chrome 45+ 已棄用,改用 CSS/Web Animations API)
function hasSMIL() {
const svg = document.createElementNS('https://www.w3.org/2000/svg', 'animate');
return 'beginElement' in svg;
}
精準偵測 SVG 支援,能確保圖表在各代瀏覽器都能正確渲染,避免空白、錯位或功能缺失。