Three.js - 如何使用自定义属性

时间:2018-04-17 23:14:18

标签: javascript three.js

我有一个用three.js

制作的2D平面图

我已经用这种方式添加了形状:

var geometry = new THREE.Geometry();
geometry.vertices.push(
    new THREE.Vector3(50, 0, 90),
    new THREE.Vector3(130, 0, 95),
    new THREE.Vector3(74, 0, -50)
);
geometry.faces.push(new THREE.Face3(0, 1, 2));

var material = new THREE.MeshBasicMaterial({ color: 0xff0000,opacity:0.9 });
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
mesh.on('click', function (ev) {
    console.log(ev);
 });

我尝试将具有部分不透明度的形状/几何图形添加到场景中,并允许用户单击它。点击后,我应该在网页上调用javascript函数,检索单击形状的唯一ID和其他自定义属性或属性。

作为活动经理,我使用three.interaction

我无法理解放置对象属性的位置并检索它们。是否可以在three.js中完成? 有没有办法在鼠标悬停时设置可点击对象的样式,比如改变它的颜色?

1 个答案:

答案 0 :(得分:0)

我已经解决了在对象的userData中添加属性的问题:

var geometry = new THREE.Geometry();
geometry.vertices.push(
    new THREE.Vector3(50, 0, 90),
    new THREE.Vector3(130, 0, 95),
    new THREE.Vector3(74, 0, -50)
);
geometry.faces.push(new THREE.Face3(0, 1, 2));

var material = new THREE.MeshBasicMaterial({ color: 0xff0000,opacity:0.9 });
var mesh = new THREE.Mesh(geometry, material);
mesh.userData.code = "12345ABC";
mesh.userData.name = "Example01";
scene.add(mesh);
mesh.on('click', function (ev) {
    console.log(ev.target.userData.code);
    ev.target.material.color.setHex( 0xffff00 );
});

我也可以用ev.target.material.color.setHex(0xffff00)改变颜色;使用mouseover和mouseout事件。