threejs点击事件(不同大小的画布)
一、直接是window宽高的画布,点击交互的方案
onClick(event) { event.preventDefault(); this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1; this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; this.raycaster.setFromCamera(this.mouse, this.camera); const intersects = this.raycaster.intersectObjects( this.boneSpheres.children ); if (intersects.length > 0) { if (this.highlightFace) { this.highlightFace.material = this.highlightFace.material0; } intersects[0].object.material0 = intersects[0].object.material; intersects[0].object.material = new THREE.MeshBasicMaterial({ color: "#FF00FF", transparent: true, opacity: 0.5, }); this.highlightFace = intersects[0].object; } return intersects; },
其中的this.boneSpheres.children,为你要点击选中的整个对象;点击选中对象,改变材质颜色;intersects[0]获取的是射线穿透中,第一个射线穿过的数据;也就是表面的数据。
二、自定义大小的画布,点击交互的方案
onClick(event) { event.preventDefault(); let canvasPosition = this.renderer.domElement.getBoundingClientRect(); this.mouse.x = event.clientX - canvasPosition.left; this.mouse.y = event.clientY - canvasPosition.top; let mouseVector = new THREE.Vector2 ( 2 * (this.mouse.x / 900) - 1, 1 - 2 * (this.mouse.y / 900)); this.raycaster.setFromCamera(mouseVector, this.camera); const intersects = this.raycaster.intersectObjects( this.boneSpheres.children ); if (intersects.length > 0) { if (this.highlightFace) { this.highlightFace.material = this.highlightFace.material0; } intersects[0].object.material0 = intersects[0].object.material; intersects[0].object.material = new THREE.MeshBasicMaterial({ color: "#FF00FF", transparent: true, opacity: 0.5, }); this.highlightFace = intersects[0].object; } return intersects; },
其中的900,为canvas画布的宽和高;其中最重要的是下面这几句:
let canvasPosition = this.renderer.domElement.getBoundingClientRect(); this.mouse.x = event.clientX - canvasPosition.left; this.mouse.y = event.clientY - canvasPosition.top; let mouseVector = new THREE.Vector2 (2 * (this.mouse.x / 900) - 1,1 - 2 * (this.mouse.y / 900)); this.raycaster.setFromCamera(mouseVector, this.camera);
如果有不懂的可以加qq技术群学习讨论:910316886
标签:threejs,material,intersects,object,画布,点击,highlightFace,mouse,event From: https://www.cnblogs.com/yaosusu/p/17243453.html