SYSTEM ONLINE

YuHuizhen.com

返回首页
Graphics 3D

WebGL 着色器魔法入门

2024/2/18 10 min

WebGL 基础

WebGL 允许我们在浏览器中渲染高性能的 2D 和 3D 图形,无需任何插件。它基于 OpenGL ES,通过 HTML5 Canvas 元素提供硬件加速的图形渲染。

着色器简介

着色器是在 GPU 上运行的小程序,用 GLSL(OpenGL Shading Language)编写。主要有两种类型:

  • 顶点着色器 - 处理每个顶点的位置
  • 片元着色器 - 决定每个像素的颜色

GLSL 基础语法

GLSL 是一种类 C 语言,专门为图形处理设计。

简单的顶点着色器

attribute vec3 position;
uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;

void main() {
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

简单的片元着色器

precision mediump float;
uniform vec3 color;

void main() {
  gl_FragColor = vec4(color, 1.0);
}

Three.js 实战

Three.js 是一个流行的 WebGL 库,它简化了 3D 图形编程。

创建自定义材质

const material = new THREE.ShaderMaterial({
  vertexShader: `
    varying vec2 vUv;
    void main() {
      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: `
    varying vec2 vUv;
    void main() {
      gl_FragColor = vec4(vUv, 0.5, 1.0);
    }
  `
});