检查是否支持WebGL
检查浏览器是否支持WebGL;
<!DOCTYPE html>
<html lang="en">
<head>
<title>检查是否支持WebGL</title>
<meta property="og:description" content="检查浏览器是否支持WebGL" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
function isWebglSupported() {
if (window.WebGLRenderingContext) {
const canvas = document.createElement('canvas');
try {
// 注意:可以传递 { failIfMajorPerformanceCaveat: true } 作为第二个参数
// 给 canvas.getContext(),如果硬件渲染不可用,检查将失败
// 更多详情,请参见:
// https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/getContext
const context = canvas.getContext('webgl2') || canvas.getContext('webgl');
if (context && typeof context.getParameter == 'function') {
return true;
}
} catch (e) {
// WebGL 支持但被禁用
}
return false;
}
// 不支持 WebGL
return false;
}
if (!isWebglSupported()) {
alert('您的浏览器不支持WebGL');
} else {
const map = new maplibregl.Map({
container: 'map',
style:
'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
center: [-74.5, 40],
zoom: 9
});
}
</script>
</body>
</html>