之前一直在捣鼓Vue和React栈,对组件化架构项目有了些理解和体会。今天尝尝WebGL,当然,并不打算现在深入,只是略作了解,我知道这个坑很深。
js的图形库、3d库也有好几款比较流行的,如游戏开发方面的three.js、数据可视化的图表库echarts.js、GIS方面的百度地图、google地图等,最近打算学习下。
言归正传,以前学canvas的时候,只是简单地学习2d context的一些api写写画画,webGL显然更高级些,在MDN文档的介绍中:
WebGL enables web content to use an API based on OpenGL ES 2.0 to perform 3D rendering in an HTML
<canvas>in browsers that support it without the use of plug-ins. WebGL programs consist of control code written in JavaScript and special effects code(shader code) that is executed on a computer's Graphics Processing Unit (GPU). WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background.
提到了WebGL可以让网页内容中的canvas元素实现3d渲染,其编程由两部分组成,一部分是由js写的控制代码,一部分是在用户设备gpu上执行的实现特定效果的代码(GLSL,注意,GLSL是一门针对GPU的编程语言)。不过WebGL只兼容IE11+
教程假设我们会一些基本的3d图像的概念。Learn WebGL for 2D and 3D graphics这篇入门教程指出,需要我们会一点html和css知识,以及较深的js功底,能理解闭包、原型链、构造函数等概念。
第一步,检测设备是否支持WebGL:
function detectWebGLContext () { // Create canvas element. The canvas is not added to the // document itself, so it is never displayed in the // browser window. var canvas = document.createElement("canvas"); // Get WebGLRenderingContext from canvas element. var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); // Report the result. if (gl && gl instanceof WebGLRenderingContext) { paragraph.innerHTML = "Congratulations! Your browser supports WebGL."; } else { paragraph.innerHTML = "Failed to get WebGL context. " + "Your browser or device may not support WebGL."; } }