This repository was archived by the owner on Feb 1, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathuseVideoTexture.ts
More file actions
74 lines (70 loc) · 2.03 KB
/
useVideoTexture.ts
File metadata and controls
74 lines (70 loc) · 2.03 KB
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
import { VideoTexture } from 'three'
import { useLogger } from '../../composables/useLogger.js'
interface VideoTextureProps extends HTMLVideoElement {
unsuspend?: 'canplay' | 'canplaythrough' | 'loadstart' | 'loadedmetadata'
start?: boolean
}
/**
* Composable for loading video textures.
*
* ```ts
* import { ref } from 'vue'
* import { useVideoTexture } from '@tresjs/cientos'
* import MyVideo from 'MyVideo.mp4'
*
* const texture = ref()
* texture.value = await useVideoTexture(MyVideo)
* ```
* Then you can use the texture in your material.
*
* ```vue
* <TresMeshBasicMaterial :map="texture" />
* ```
* @see https://threejs.org/docs/index.html?q=video#api/en/textures/VideoTexture
* @export
* @param {HTMLVideoElement} src
* @return {VideoTexture} {VideoTexture}
*/
export async function useVideoTexture(src: string | MediaStream, options?: Partial<VideoTextureProps>) {
/**
* Load a video as a texture.
*
* @param {src} string
* @return {VideoTexture} {VideoTexture}
*/
const { logError } = useLogger()
if (!src) { return logError('Error no path provided') }
const { unsuspend, start, crossOrigin, muted, loop, ...rest } = {
unsuspend: 'loadedmetadata',
crossOrigin: 'Anonymous',
muted: true,
loop: true,
start: true,
playsInline: true,
...options,
}
function loadTexture(): Promise<VideoTexture> {
return new Promise((resolve, reject) => {
const video = Object.assign(document.createElement('video'), {
src: (typeof src === 'string' && src) || undefined,
crossOrigin,
loop,
muted,
autoplay: true,
...rest,
})
const texture = new VideoTexture(video)
video.addEventListener(unsuspend, () => resolve(texture))
video.addEventListener('error', () => reject(new Error('Error loading video')))
return texture
})
}
try {
const texture = await loadTexture()
if (start && texture.image) { texture.image.play() }
return texture
}
catch {
logError('Error loading resource')
}
}