案例展示
原始着色器效果
TIP
经典 GLSL RawShaderMaterial 仅 WebGL 模式可用(
renderer: 'webgl')。
<template>
<div id="TO"></div>
</template>
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
// 经典 GLSL RawShaderMaterial 仅兼容 WebGL(renderQuality 须写在 scene 下)
new ThingOrigin(
'fileModel',
document.getElementById('TO'),
{
scene: {
renderQuality: {
renderer: 'webgl'
},
ground: {
//设置地面
active: false
},
background: {
type: 'color', //设置背景颜色
color: {
alpha: 1, // 透明度 取值范围0~1
color: '#000000' // 背景颜色
}
}
},
camera: {
// 相机配置
position: {
// 相机位置
x: 0,
y: 50,
z: 200
}
},
helper: {
//辅助工具
axes: {
active: false
},
grid: {
active: false
}
}
},
(TO) => {
//顶点着色器代码
var vertexShader = `
attribute vec3 position;//position变量从PlaneBufferGeometry的position属性中获取顶点信息
varying vec3 v_position;
void main() {
v_position = position;
gl_Position = vec4( position, 1.0 );
}
`
//片元着色器代码
var fragmentShader = `
#ifdef GL_ES
precision mediump float;
#endif
varying vec3 v_position;
uniform float radius;
void main( void ) {
vec3 center = vec3(.0,.0,.0);
float dist = distance(center,v_position);//计算中心到顶点的距离
dist = clamp(dist,0.0,1.0);//将距离限制在0~1
float color = 1.0 - dist;
if(dist >radius-0.3&&dist < radius-0.28||dist >radius-0.4&&dist < radius-0.38){
gl_FragColor = vec4(1.0*color,0.6*color,0.6*color,1.0);//绘制两层光圈
}else{
gl_FragColor = vec4(color*radius,0.0,0.0,1.0);//绘制底色
}
}`
//创建着色器材质
var shaderMaterial = TO.material.initRawShaderMaterial({
vertexShader: vertexShader,
fragmentShader: fragmentShader,
uniforms: {
radius: {
type: 'f',
value: 0.2
}
}
})
//创建平面
TO.model
.initPlane({
position: {
x: -30,
y: 5,
z: 0
}
})
.then((planeMesh) => {
planeMesh.material = shaderMaterial
//添加到场景中
TO.scene.add(planeMesh)
setInterval(() => {
//更新光圈半径
planeMesh.material.uniforms['radius'].value += 1.0 / 60.0
if (planeMesh.material.uniforms.radius.value > 1) {
planeMesh.material.uniforms.radius.value = 0
}
}, 200)
})
}
)
})
</script>
<style scoped>
#TO {
width: 100%;
height: 400px;
position: relative;
}
</style>API 介绍
material.initRawShaderMaterial
| 方法签名 | 返回值 | 描述 |
|---|---|---|
initRawShaderMaterial(params: Partial<ShaderMaterialParameters> = {}) | RawShaderMaterial | 创建原始着色器材质 |
ShaderMaterialParameters 参数说明:
| 参数名 | 说明 | 类型 | 必填 | 默认值 |
|---|---|---|---|---|
vertexShader | 顶点着色器的 GLSL 代码 | string | - | - |
fragmentShader | 片元着色器的 GLSL 代码 | string | - | - |
uniforms | Uniforms 变量 | { [p: string]: IUniform<any> } | - | - |
transparent | 是否开启透明度 | boolean | - | false |
side | 渲染面:FrontSide(正面)、BackSide(背面)、DoubleSide(双面) | string | - | FrontSide |