Skip to content

Raycaster Measurements

Description

Using the Raycaster to assist in measuring the distance between points.

This example demonstrates,

  • Using the Raycaster, along with pointer events to start and draw a line from point A to B.
  • Using the CSS2DRenderer and CSS2DObject to create measurement labels.
  • Using Vector3.lerpVectors to position a label between 2 points.

Start Code

./src/server/server.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import express from "express"
import path from "path"
import http from "http"

const port: number = 3000

class App {
    private server: http.Server
    private port: number

    constructor(port: number) {
        this.port = port
        const app = express()
        app.use(express.static(path.join(__dirname, '../client')))
        app.use('/build/three.module.js', express.static(path.join(__dirname, '../../node_modules/three/build/three.module.js')))
        app.use('/jsm/controls/OrbitControls', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/controls/OrbitControls.js')))
        app.use('/jsm/loaders/GLTFLoader', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/loaders/GLTFLoader.js')))
        app.use('/jsm/libs/stats.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/stats.module.js')))
        app.use('/jsm/libs/dat.gui.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/dat.gui.module.js')))
        app.use('/jsm/renderers/CSS2DRenderer', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/renderers/CSS2DRenderer.js')))

        this.server = new http.Server(app);
    }

    public Start() {
        this.server.listen(this.port, () => {
            console.log(`Server listening on port ${this.port}.`)
        })
    }
}

new App(port).Start()

./src/client/client.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import { GLTFLoader } from '/jsm/loaders/GLTFLoader'
import Stats from '/jsm/libs/stats.module'
import { CSS2DRenderer, CSS2DObject } from '/jsm/renderers/CSS2DRenderer';

const scene: THREE.Scene = new THREE.Scene()

var light = new THREE.SpotLight()
light.position.set(12.5, 12.5, 12.5)
light.castShadow = true
light.shadow.mapSize.width = 1024;
light.shadow.mapSize.height = 1024;
scene.add(light)

const camera: THREE.PerspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.x = 15
camera.position.y = 15
camera.position.z = 15

const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer()
renderer.shadowMap.enabled = true
renderer.outputEncoding = THREE.sRGBEncoding
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const labelRenderer = new CSS2DRenderer()
labelRenderer.setSize(window.innerWidth, window.innerHeight)
labelRenderer.domElement.style.position = 'absolute'
labelRenderer.domElement.style.top = '0px'
labelRenderer.domElement.style.pointerEvents = 'none'
document.body.appendChild(labelRenderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

const pickableObjects: THREE.Mesh[] = new Array()

const loader = new GLTFLoader()
loader.load(
    'models/simplescene.glb',
    function (gltf) {
        gltf.scene.traverse(function (child) {
            if ((<THREE.Mesh>child).isMesh) {
                let m = <THREE.Mesh>child
                switch (m.name) {
                    case "Plane":
                        m.receiveShadow = true
                        break
                    default:
                        m.castShadow = true
                }
                pickableObjects.push(m)
            }
        })
        scene.add(gltf.scene)
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total * 100) + '% loaded')
    },
    (error) => {
        console.log(error);
    }
);

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    labelRenderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

let ctrlDown = false
let lineId = 0
let line: THREE.Line
let drawingLine = false
const measurementLabels: { [key: number]: CSS2DObject } = {}

window.addEventListener('keydown', function (event) {
    if (event.key === "Control") {
        ctrlDown = true
        controls.enabled = false
        renderer.domElement.style.cursor = "crosshair";
    }
});

window.addEventListener('keyup', function (event) {
    if (event.key === "Control") {
        ctrlDown = false
        controls.enabled = true
        renderer.domElement.style.cursor = "pointer";
        if (drawingLine) {
            //delete the last line because it wasn't committed
            scene.remove(line)
            scene.remove(measurementLabels[lineId]);
            drawingLine = false
        }
    }
});

const raycaster = new THREE.Raycaster()
let intersects: THREE.Intersection[]
const mouse = new THREE.Vector2();

renderer.domElement.addEventListener('pointerdown', onClick, false);
function onClick(event: MouseEvent) {
    if (ctrlDown) {
        raycaster.setFromCamera(mouse, camera)
        intersects = raycaster.intersectObjects(pickableObjects, false);
        if (intersects.length > 0) {
            if (!drawingLine) {
                //start the line
                const points = [];
                points.push(intersects[0].point)
                points.push(intersects[0].point.clone())
                const geometry = new THREE.BufferGeometry().setFromPoints(points);
                line = new THREE.LineSegments(geometry, new THREE.LineBasicMaterial({
                    color: 0xffffff,
                    transparent: true,
                    opacity: 0.75
                    // depthTest: false,
                    // depthWrite: false
                }))
                line.frustumCulled = false
                scene.add(line)

                const measurementDiv = document.createElement('div') as HTMLDivElement
                measurementDiv.className = 'measurementLabel'
                measurementDiv.innerText = "0.0m"
                const measurementLabel = new CSS2DObject(measurementDiv);
                measurementLabel.position.copy(intersects[0].point);
                measurementLabels[lineId] = measurementLabel;
                scene.add(measurementLabels[lineId]);
                drawingLine = true;

            } else {
                //finish the line
                const positions = line.geometry.attributes.position.array as Array<number>
                positions[3] = intersects[0].point.x
                positions[4] = intersects[0].point.y
                positions[5] = intersects[0].point.z
                line.geometry.attributes.position.needsUpdate = true 
                lineId++
                drawingLine = false
            }
        }
    }
}

document.addEventListener('mousemove', onDocumentMouseMove, false);
function onDocumentMouseMove(event: MouseEvent) {

    event.preventDefault();

    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;

    if (drawingLine) {
        raycaster.setFromCamera(mouse, camera)
        intersects = raycaster.intersectObjects(pickableObjects, false);
        if (intersects.length > 0) {
            const positions = line.geometry.attributes.position.array as Array<number>
            const v0 = new THREE.Vector3(positions[0], positions[1], positions[2])
            const v1 = new THREE.Vector3(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z)
            positions[3] = intersects[0].point.x
            positions[4] = intersects[0].point.y
            positions[5] = intersects[0].point.z          
            line.geometry.attributes.position.needsUpdate = true  
            const distance = v0.distanceTo(v1)
            measurementLabels[lineId].element.innerText = distance.toFixed(2) + "m"
            measurementLabels[lineId].position.lerpVectors(v0, v1, .5)
        }
    }
}

const stats = Stats()
document.body.appendChild(stats.dom)

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

    render()

    stats.update()
};

function render() {
    labelRenderer.render(scene, camera)
    renderer.render(scene, camera)
}
animate();

./src/dist/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>

<head>
    <title>Three.js TypeScript Tutorials by Sean Bradley</title>
    <style>
        body {
            overflow: hidden;
            margin: 0px;
        }

        .measurementLabel{
            font-family: monospace;
            background-color: black;
            color: white;
        }
    </style>
</head>

<body>
    <script type="module" src="client.js"></script>
</body>

</html>