three.js改变几何体颜色
·
效果如图点击几何体的其中一个面改变这个面的颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{margin:auto;
overflow: hidden;
}
</style>
</head>
<body>
<div id="webgl"></div>
<script src="../libs/three.js"></script>
<script src="../libs/dat.gui.js"></script>
<script>
function main(){
//渲染器
var renderer=new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth,window.innerHeight);
renderer.setClearColor(0xffffff);
//相机
var camera=new THREE.PerspectiveCamera(60,window.innerWidth/window.innerHeight,0.1,1000);
//场景
var scene=new THREE.Scene();
var mesh1=new THREE.MeshBasicMaterial({color:0xff0000,side:THREE.DoubleSide})
var mesh2=new THREE.MeshBasicMaterial({color:0x00ff00,side:THREE.DoubleSide})
var mesh3=new THREE.MeshBasicMaterial({color:0x0000ff,side:THREE.DoubleSide})
var mesh=new THREE.MeshFaceMaterial([mesh1,mesh1,mesh2,mesh2,mesh3,mesh3,mesh1,mesh1,mesh2,mesh2,mesh3,mesh3])
var box=new THREE.BoxGeometry(20,20,20)
//改变的颜色
var color=[new THREE.Color(0xff0000),new THREE.Color(0xffff33),new THREE.Color(0x00dd00),
new THREE.Color(0xcc0000),new THREE.Color(0x6600ff),new THREE.Color(0x00cccc),new THREE.Color(0xff00ff),
new THREE.Color(0x00ffff)]
function down(event){
//世界坐标转屏幕坐标
var vector = new THREE.Vector3(( event.clientX / window.innerWidth ) * 2 - 1, -( event.clientY / window.innerHeight ) * 2 + 1, 0.5);
vector = vector.unproject(camera);
var raycaster=new THREE.Raycaster(camera.position,vector.sub(camera.position).normalize())
var intersects=raycaster.intersectObjects([gemo])
//判断是否点击几何体
if(intersects.length>0){
mesh.materials[intersects[0].face.materialIndex].color.copy(
color[Math.floor(Math.random()*color.length)]
)
}
}
document.onmousedown=down
var gemo=new THREE.Mesh(box,mesh);
gemo.material=mesh;
gemo.material.needsUpdate=true;
scene.add(gemo);
camera.position.set(0,30,40)
camera.lookAt(scene.position)
var step=0.02;
function render(){
gemo.rotation.x=step;
gemo.rotation.y=step
gemo.rotation.z=step
step+=0.02
renderer.render(scene,camera)
requestAnimationFrame(render)
}
requestAnimationFrame(render)
renderer.render(scene,camera);
document.getElementById('webgl').appendChild(renderer.domElement);
}
window.onload=main;
</script>
</body>
</html>
更多推荐
已为社区贡献1条内容
所有评论(0)