Skip to main content

Video Textures

Try it from the Editor in the tutorial project.

This project creates a texture and runtime, downloads and plays a video file and renders the video into the texture. This texture is then applied to a model and used in the scene.

This script performs the following functions:

  • Create new Texture
  • Create an HTML Video element and play the video
  • Apply the new texture to the material on the TV model
  • Update the texture with video data every frame
import {
Asset,
Script,
Texture,
PIXELFORMAT_RGB8,
FILTER_LINEAR,
FILTER_LINEAR_MIPMAP_LINEAR,
ADDRESS_CLAMP_TO_EDGE
} from 'playcanvas';

/**
* Creates and manages a video texture, loading from an asset or URL, and triggering an event when ready.
*/
export class VideoTexture extends Script {
static scriptName = 'videoTexture';

/**
* MP4 video asset to play back on this video texture.
*
* @attribute
* @title Video Asset
* @type {Asset}
*/
videoAsset;

/**
* URL to use if there is no video asset selected.
*
* @attribute
* @title Video Url
* @type {string}
*/
videoUrl;

/**
* Event that is fired as soon as the video texture is ready to play.
*
* @attribute
* @title Play Event
* @type {string}
* @default ''
*/
playEvent = '';

initialize() {
const app = this.app;

// Create an HTML video element to play the video
const video = document.createElement('video');
video.loop = true;

// Videos must be muted to autoplay
video.muted = true;

// Critical for iOS, or the video won't play at first and goes fullscreen when it does
video.playsInline = true;

// Needed because the video is hosted on a different origin
video.crossOrigin = 'anonymous';

video.autoplay = true;

// iOS only plays a video texture if the video is in the DOM and at least 1x1 in size
Object.assign(video.style, {
width: '1px',
height: '1px',
position: 'absolute',
opacity: '0',
zIndex: '-1000',
pointerEvents: 'none'
});

document.body.appendChild(video);

// Create a texture to hold the video frame data
this.videoTexture = new Texture(app.graphicsDevice, {
format: PIXELFORMAT_RGB8,
minFilter: FILTER_LINEAR_MIPMAP_LINEAR,
magFilter: FILTER_LINEAR,
addressU: ADDRESS_CLAMP_TO_EDGE,
addressV: ADDRESS_CLAMP_TO_EDGE,
mipmaps: true
});

this.videoTexture.setSource(video);
this.video = video;

// Play the video and fire the event when ready
video.addEventListener('canplaythrough', () => {
app.fire(this.playEvent, this.videoTexture);
video.play();
});

video.src = this.videoAsset ? this.videoAsset.getFileUrl() : this.videoUrl;
video.load();

this.on('destroy', () => {
this.videoTexture.destroy();
video.remove();
});
}

update(dt) {
// Transfer the latest video frame to the video texture
this.videoTexture.upload();
}
}