<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Add a 3D model with threebox</title>
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
/>
<link
href="https://api.mapbox.com/mapbox-gl-js/v3.10.0/mapbox-gl.css"
rel="stylesheet"
/>
<script src="https://api.mapbox.com/mapbox-gl-js/v3.10.0/mapbox-gl.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<script
src="https://cdn.jsdelivr.net/gh/jscastro76/threebox@v.2.2.2/dist/threebox.min.js"
type="text/javascript"
></script>
<link
href="https://cdn.jsdelivr.net/gh/jscastro76/threebox@v.2.2.2/dist/threebox.css"
rel="stylesheet"
/>
<div id="map"></div>
<script>
const glbUrl =
"https://docs.mapbox.com/mapbox-gl-js/assets/metlife-building.gltf";
const scale = 0;
const options = {
obj: glbUrl,
type: "gltf",
scale: { x: scale, y: scale, z: 0 },
units: "meters",
rotation: { x: 0, y: 0, z: 0 },
};
mapboxgl.accessToken =
"pk.eyJ1IjoiaHVhbmdsaWkiLCJhIjoiY2wwM2E4a2drMDVrZjNrcGRucHIxOHo0cyJ9.0ecG5KGQE6R-SmhxvLvhHg";
const init = () => {
map = new mapboxgl.Map({
container: "map",
center: [114.33, 30.57],
zoom: 14,
});
map.on("load", () => {
tb = window.tb = new Threebox(
map,
map.getCanvas().getContext("webgl"),
{
defaultLights: true,
}
);
map.addLayer({
id: "custom-threebox-model",
type: "custom",
renderingMode: "3d",
onAdd: function () {
tb.loadObj(options, (model) => {
model_Value = model;
model_Value.setRotation({ x: 0, y: 0, z: 0 });
model_Value.setCoords([114.33, 30.57, 100]);
tb.add(model_Value);
});
},
render: function () {
tb.update();
},
});
map.on("click", (e) => {
const mousePos = new THREE.Vector2(
(e.point.x / map.getCanvas().width) * 2 - 1,
-(e.point.y / map.getCanvas().height) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mousePos, tb.camera);
const intersects = raycaster.intersectObject(model_Value, true);
if (intersects.length > 0) {
const object = intersects[0].object;
console.log("Clicked on:", object);
object.material.color.set(0xff0000);
}
});
});
};
init();
</script>
</body>
</html>