THREEJS(版本85)实现鼠标点击的高亮显示(如颜色变化)
啥也不多说,看效果图:
鼠标点击时,发生颜色变化(可以引申出去做很多其他的操作)
代码:首先初始化:
var objects=[]; var raycaster= new THREE.Raycaster(); var mouse = new THREE.Vector2(), INTERSECTED, SELECTED;
需要把你要实现的效果的geometry加载到objects中
var shape32=createMesh(lines[32]); objects.push(shape32); scene.add(shape32);注:createMesh自己随便写的
鼠标点击事件:
function onDocumentMouseDown( event ) { event.preventDefault(); document.addEventListener( 'mousemove', onDocumentMouseMove, false ); document.addEventListener( 'mouseup', onDocumentMouseUp, false ); document.addEventListener( 'mouseout', onDocumentMouseOut, false ); //鼠标点的拾取-当鼠标点击效果时,放在这里 mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;//threejs坐标点的标准化 mouse.y = - ( event.clientY / window.innerHeight) * 2 + 1; raycaster.setFromCamera( mouse, camera ); var intersects = raycaster.intersectObjects( objects ); //拾取物体数大于0时 if ( intersects.length > 0 ) { //获取第一个物体 if (SELECTED != intersects[0].object) { //鼠标的变换 document.body.style.cursor='pointer'; /*intersects[ 0 ].object.material.transparent=true;//透明度的变化 intersects[ 0 ].object.material.opacity=0.5;*/ if (SELECTED) SELECTED.material.color.setHex(SELECTED.currentHex); SELECTED = intersects[0].object; SELECTED.currentHex = SELECTED.material.color.getHex();//记录当前选择的颜色 //改变物体的颜色(红色) SELECTED.material.color.set( 0x66ff00 ); } } else { document.body.style.cursor= 'auto'; if (SELECTED) SELECTED.material.color.set(SELECTED.currentHex);//恢复选择前的默认颜色 SELECTED = null; } }
完美**********************************************************************华丽分割线*******************************************************************************END