我们前面学习了三角面,知道一个立方体是由顶点(vectors)和索引(faces)坐标才可以画出来的。
uv是用来描述纹理位置的,也就是需要标注图片四个顶点的位置。不过这个位置坐标比较特殊,值必须是在0~1之间的。请看下图:
bear.png
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>
<script src="http://www.yanhuangxueyuan.com/threejs/examples/js/controls/OrbitControls.js"></script>
<title>Document</title>
</head>
<body>
<div id="webgl"></div>
</body>
</html>
<script>
var scene = new THREE.Scene();
//添加坐标轴
var axes = new THREE.AxesHelper(300);//50表示xyz轴的长度,红:x,绿:y,蓝:z
scene.add(axes);
var geometry = new THREE.BufferGeometry();
console.log(geometry);
var points = new Float32Array([
-5, 5, 5,
5, 5, 5,
5, 5, -5,
-5, 5, -5
]);
var index = [
0,1,2,
2,3,0
];
var uv =new Float32Array([
0,0,
1,0,
1,1,
0,1
]);
geometry.addAttribute('position', new THREE.BufferAttribute(points, 3));
geometry.setIndex(index);
geometry.addAttribute('uv',new THREE.BufferAttribute(uv,2));
const textureLoader = new THREE.TextureLoader();
const textureUrl = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F512%2F040912153611%2F120409153611-11.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642141424&t=949616f6854cb89898a29553af2e53ff';
var material = new THREE.MeshBasicMaterial({
map: textureLoader.load(textureUrl)
}); //材质对象Material
var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
scene.add(mesh);
//创建相机对象
var camera = new THREE.PerspectiveCamera(45, 2, 0.1, 2000);
camera.position.set(20, 20, 20); //设置相机位置
camera.lookAt(new THREE.Vector3(0, 0, 0)); //设置相机方向(指向的场景对象)
/**
* 创建渲染器对象
*/
var renderer = new THREE.WebGLRenderer({
antialias: true //消除锯齿
});
renderer.setSize(1000, 500);//设置渲染区域尺寸
renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
renderer.render(scene, camera);//渲染必须有场景和相机两个对象
var cont = document.getElementById('webgl');
cont.appendChild(renderer.domElement);
//增加鼠标拾取效果
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.addEventListener('change', () => {
renderer.render(scene, camera);
});
</script>
img.gif
网友评论