WebGL兼容性检查

发布时间:2024年01月09日

引入文件WebGL.js

class WebGL {

  static isWebGLAvailable () {

    try {

      const canvas = document.createElement('canvas');
      return !!(window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));

    } catch (e) {

      return false;

    }

  }

  static isWebGL2Available () {

    try {

      const canvas = document.createElement('canvas');
      return !!(window.WebGL2RenderingContext && canvas.getContext('webgl2'));

    } catch (e) {

      return false;

    }

  }

  static isColorSpaceAvailable (colorSpace) {

    try {

      const canvas = document.createElement('canvas');
      const ctx = window.WebGL2RenderingContext && canvas.getContext('webgl2');
      ctx.drawingBufferColorSpace = colorSpace;
      return ctx.drawingBufferColorSpace === colorSpace; // deepscan-disable-line SAME_OPERAND_VALUE

    } catch (e) {

      return false;

    }

  }

  static getWebGLErrorMessage () {

    return this.getErrorMessage(1);

  }

  static getWebGL2ErrorMessage () {

    return this.getErrorMessage(2);

  }

  static getErrorMessage (version) {

    const names = {
      1: 'WebGL',
      2: 'WebGL 2'
    };

    const contexts = {
      1: window.WebGLRenderingContext,
      2: window.WebGL2RenderingContext
    };

    let message = 'Your $0 does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">$1</a>';

    const element = document.createElement('div');
    element.id = 'webglmessage';
    element.style.fontFamily = 'monospace';
    element.style.fontSize = '13px';
    element.style.fontWeight = 'normal';
    element.style.textAlign = 'center';
    element.style.background = '#fff';
    element.style.color = '#000';
    element.style.padding = '1.5em';
    element.style.width = '400px';
    element.style.margin = '5em auto 0';

    if (contexts[version]) {

      message = message.replace('$0', 'graphics card');

    } else {

      message = message.replace('$0', 'browser');

    }

    message = message.replace('$1', names[version]);

    element.innerHTML = message;

    return element;

  }

}

export default WebGL;

JS中使用

import WebGL from './WebGL.js';

if (WebGL.isWebGLAvailable()) {

  // Initiate function or other initializations here
  console.log('支持WebGL')
} else {

	// 不支持WebGL

}
文章来源:https://blog.csdn.net/AIB_Kasic/article/details/135483765
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。