模型高亮选择
通过移动鼠标高亮三维模型。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>模型高亮选择</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no"/>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
<script src="https://delivery.mapmost.com/cdn/sdk/webgl/v9.4.1/mapmost-webgl-min.js"></script>
</head>
<body>
<div id="map"></div>
<script>
let map = new mapmost.Map({
container: 'map',
style: "<your style url>",
center: [120.69647280968667, 31.35628749488366],
zoom: 18,
pitch: 60,
bearing: -7.200086687507338,
userId: '***', // 授权码
env3D: {
exposure: 2.0,
envMap: '../../../../static/example_data/hdr/WhiteBG_Ref_1K.hdr'
}
});
let THREE = mapmost.THREE;
map.on('load', function () {
let modelLayer,selectedObj;
// 添加模型
let models_obj = [{
type: 'glb',
url: "../example_data/house.glb"
}];
const center = [120.69647280968667, 31.35628749488366];
let options = {
id: 'model_id',
type: 'model',
callback: function (group, layer) {
modelLayer = layer;
// 添加 house
modelLayer.addModel(models_obj, center);
}
};
map.addLayer(options);
// 添加鼠标 hover 事件
map.on('mousemove', function (e) {
if (modelLayer) {
selectObj(e.point)
}
});
// 根据屏幕鼠标位置选择模型
function selectObj(point) {
let intersect = modelLayer.selectModel(point)[0];
if (intersect) {
let nearestObject = intersect.object;
// 选中的不是之前选中的层
if (!(selectedObj === nearestObject.parent)) {
_remove();
selectedObj = nearestObject.parent;
selectedObj.traverse(function (child) {
if (child instanceof THREE.Mesh) {
// 将原有材质存储到自定义属性
child.baseMaterial = child.material;
// 复制原有的材质并修改颜色
child.material = child.material.clone();
child.material.color = new THREE.Color(0xffff00);
}
});
}
} else {
_remove();
}
}
// 还原
function _remove() {
if (selectedObj) {
selectedObj.traverse(function (child) {
child.material = child.baseMaterial;
});
selectedObj = undefined;
}
}
})
</script>
</body>
</html>