<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>05.WebGL转ThreeJs</title>
<script src="js/three.js"></script>
<!-- 顶点着色器 -->
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
uniform mat4 uMVMatrix;
uniform mat4 uNMatrix;
uniform vec3 uAmbientColor;
uniform vec3 uLightingDirection;
uniform vec3 uDirectionalColor;
varying vec2 vTextureCoord;
varying vec3 vLightWeighting;
void main(void) {
gl_Position = uMVMatrix * vec4(aVertexPosition, 1.0);
vTextureCoord = aTextureCoord;
vec3 transformedNormal = (uNMatrix * vec4(aVertexNormal, 1.0)).xyz;
float directionalLightWeighting = max(dot(transformedNormal, uLightingDirection), 0.0);
vLightWeighting = uAmbientColor + uDirectionalColor * directionalLightWeighting;
}
</script>
<!-- 片源着色器 -->
<script id="shader-fs" type="x-shader/x-fragment">
precision mediump float;
uniform sampler2D uSampler;
uniform float uAlpha;
varying vec2 vTextureCoord;
varying vec3 vLightWeighting;
void main(void) {
vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
gl_FragColor = vec4(textureColor.rgb * vLightWeighting, textureColor.a * uAlpha);
}
</script>
</head>
<body>
<script>
var width = 50;
var height = 50;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 10000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(10, 10, 10).normalize();
scene.add(light);
// 顶点
var geometry = new THREE.BufferGeometry();
var vertices = new Float32Array([
0, 0, 0, // 0
1.0, 0, 0, // 1
1.0, 1.0, 0, // 2
0, 1.0, 0, // 3
0, 0, 1.0, // 4
1.0, 0, 1.0, // 5
1.0, 1.0, 1.0, // 6
0, 1.0, 1.0 // 7
]);
geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
// 索引
var index = [
// 前面
0, 1, 2,
0, 2, 3,
// 后面
4, 7, 6,
4, 6, 5,
// 上面
3, 2, 6,
3, 6, 7,
// 下面
0, 4, 5,
0, 5, 1,
// 左面
0, 3, 7,
0, 7, 4,
// 右面
1, 5, 6,
1, 6, 2
];
geometry.setIndex(index);
var material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
camera.position.set(0, 0, 10);
camera.lookAt(new THREE.Vector3(0, 0, 0));
var render = function () {
requestAnimationFrame(render);
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.01;
renderer.render(scene, camera);
}
render();
</script>
</body>
</html>
05、WebGL转ThreeJs
创建日期:2024-07-08
更新日期:2024-07-08
简介
一个来自三线小城市的程序员开发经验总结。