Skip to content

Commit c7ed68b

Browse files
committed
Keep text box inside the screen bounds
1 parent 97f0193 commit c7ed68b

File tree

1 file changed

+22
-24
lines changed

1 file changed

+22
-24
lines changed

src/Text.jsx

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import {
77
Color,
88
DoubleSide,
99
Quaternion,
10-
MathUtils,
1110
} from 'three'
1211
import TextGeometry from './TextGeometry'
1312
import robotoFont from './fonts/roboto/regular.json'
@@ -185,33 +184,14 @@ export const Text = ({
185184
const factor = size.width / viewWidth
186185
const scale = fontSize / (factor * font.data.info.size)
187186

188-
const bounds = {
189-
x: {
190-
min: -viewWidth / 2 - worldPosition.x + (boxSize.x * scale) / 2,
191-
max: viewWidth / 2 - worldPosition.x - (boxSize.x * scale) / 2,
192-
},
193-
y: {
194-
min: -viewHeight / 2 - worldPosition.y + (boxSize.y * scale) / 2,
195-
max: viewHeight / 2 - worldPosition.y - (boxSize.y * scale) / 2,
196-
},
197-
}
198-
199187
const placementOffset = {
200188
x: (viewWidth * positionHorz) / 100 - viewWidth / 2,
201189
y: viewHeight / 2 - (viewHeight * positionVert) / 100,
202190
}
203191

204192
const position = [
205-
MathUtils.clamp(
206-
anchorOffset.x * scale + placementOffset.x,
207-
bounds.x.min,
208-
bounds.x.max
209-
),
210-
MathUtils.clamp(
211-
anchorOffset.y * scale + placementOffset.y,
212-
bounds.y.min,
213-
bounds.y.max
214-
),
193+
anchorOffset.x * scale + placementOffset.x,
194+
anchorOffset.y * scale + placementOffset.y,
215195
0,
216196
]
217197

@@ -221,12 +201,30 @@ export const Text = ({
221201
)
222202

223203
const rotation = worldQuaternion
204+
.clone()
224205
.conjugate()
225206
.multiply(camera.quaternion)
226207
.multiply(upright)
227208

228-
// We apply the rotation to the position to make sure we are moving in relation to the camera
229-
self.position.set(...position).applyQuaternion(rotation)
209+
const viewBox = new Vector3(viewWidth, viewHeight, 0)
210+
const textSize = new Vector3(boxSize.x, boxSize.y, 0).multiplyScalar(scale)
211+
const b = viewBox.clone().sub(textSize).multiplyScalar(0.5)
212+
213+
const zero = new Vector3(0, 0, 0)
214+
const a = worldPosition
215+
.clone()
216+
.applyQuaternion(camera.quaternion.clone().conjugate())
217+
const bl = a.clone().add(b).min(zero)
218+
const ur = a.clone().multiplyScalar(-1).add(b).min(zero)
219+
const adj = ur.clone().sub(bl).setZ(0)
220+
221+
adj.applyQuaternion(
222+
worldQuaternion.clone().conjugate().multiply(camera.quaternion)
223+
)
224+
225+
const x = new Vector3(...position).add(adj)
226+
227+
self.position.copy(x)
230228
self.setRotationFromQuaternion(rotation)
231229
self.scale.set(scale, scale, scale)
232230
})

0 commit comments

Comments
 (0)