1.雾
1)片元着色器
precision mediump float;
#define LOG2 1.442695
uniform vec3 uFogColor;//雾颜色
uniform float uFogDensity;//雾强度
varying vec3 vColor;
varying vec4 vPosition;
void main() {
float fogDistance = length(vPosition.xyz );
// exp2雾
float fogAmount = 1.0- exp2(-uFogDensity * uFogDensity * fogDistance * fogDistance * LOG2);
fogAmount = clamp(fogAmount, 0.0, 1.0);
gl_FragColor = mix(vec4(vColor,1.0), vec4(uFogColor,1.0), fogAmount);
}
2) 初始化赋值
//雾颜色
gl.uniform3f(gl.getUniformLocation(program, 'uFogColor'), 0.1, 0.2, 0.4);
//雾强度
gl.uniform1f(gl.getUniformLocation(program, 'uFogDensity'), 0.2);
可以看到雾的效果近看能看清,远看变模糊。
2.旋转物体
1)监听canvas动作
function initEvent(gl) {
var rotateAngle = {
x: 0, //绕y轴旋转角度
y: 0 //绕x轴旋转角度
};
var incAngle = -0.01; //旋转角度步长值,鼠标旋转灵敏度
var lastClickX, lastClickY; //上次触控点X,Y坐标
var ismoved = false; //是否移动标志位
//鼠标按下的监听
document.onmousedown = function (event) {
var x = event.clientX;
var y = event.clientY;
//如果鼠标在canvas里开始移动
var rect = (event.target || event.srcElement).getBoundingClientRect();
if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
ismoved = true;
lastClickX = x;
lastClickY = y;
}
};
//鼠标抬起的监听
document.onmouseup = function (event) {
ismoved = false;
};
//鼠标移动时的监听
document.onmousemove = function (event) {
var x = event.clientX,
y = event.clientY;
if (ismoved) {
rotateAngle.y = rotateAngle.y + (x - lastClickX) * incAngle;
rotateAngle.x = rotateAngle.x + (y - lastClickY) * incAngle;
}
lastClickX = x;
lastClickY = y;
};
return rotateAngle;
}
2)赋值旋转角度到变换矩阵
var rotateAngle = initEvent(gl);
var modelViewMatrix = mat4.create();
mat4.rotateX(modelViewMatrix, modelViewMatrix, rotateAngle.x);
mat4.rotateY(modelViewMatrix, modelViewMatrix, rotateAngle.y);
gl.uniformMatrix4fv(
gl.getUniformLocation(gl.program, 'uModelViewMatrix'),
false,
modelViewMatrix
);
Github地址
https://github.com/xiaolidan00/my-webgl
参考
https://webglfundamentals.org/
- 《WebGL编程指南》
- 《webGL 3D开发实战详解 第2版》