import { AliRtcPlugin, LocalStreamInfo } from 'aliyun-rtc-sdk';
export default class UserNamePlugin extends AliRtcPlugin {
private canvas: HTMLCanvasElement;
private requestId?: number;
// text specifies the username that want to draw.
constructor(text: string) {
super('UserNamePlugin'); // The custom name of the plug-in, which must be globally unique.
this.options = { text };
this.canvas = document.createElement('canvas');
}
isSupported(): boolean {
// The plug-in does not need to depend on the features of a specific version of aliyun-rtc-sdk. Therefore, set the value to true.
return true;
}
setOptions(options: { text: string }): void {
// Specify whether to dynamically update the username that you want to draw.
this.options = options;
}
shouldUpdate(): boolean {
// Specify whether to call the process method when the stream status changes, for example, when the camera is turned on or off. In this example, set the value to true.
return true;
}
process(streamInfo: LocalStreamInfo): Promise<void> {
if (streamInfo.currentVideoTrack) {
// If a video track exists, define the handling method of the video track.
const videoTrack = streamInfo.currentVideoTrack as MediaStreamVideoTrack;
const settings = videoTrack.getSettings();
// Adjust the width and height of the canvas to be the same as those of the video stream.
this.canvas.width = settings.width!;
this.canvas.height = settings.height!;
// Convert the MediaStreamTrack object to the source of the video element.
const stream = new MediaStream([videoTrack]);
const videoElement = document.createElement('video');
videoElement.srcObject = stream;
videoElement.play();
const ctx = this.canvas.getContext('2d')!;
// Draw video frames to the canvas at regular intervals and add the text.
const drawFrame = () => {
if (videoElement.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
ctx.drawImage(videoElement, 0, 0, this.canvas.width, this.canvas.height);
// Add the text in the lower-right corner.
ctx.fillStyle = 'white'; // The color of the text.
ctx.font = '40px Arial'; // The size and font of the text.
ctx.textAlign = 'right'; // The alignment direction of the text.
ctx.fillText(this.options.text, this.canvas.width - 20, this.canvas.height - 20); // The position of the text.
}
this.requestId = requestAnimationFrame(drawFrame); // Continuously draw frames.
}
this.requestId = requestAnimationFrame(drawFrame);
// Create a new MediaStream object.
const newStream = this.canvas.captureStream(settings.frameRate); // Alternatively, specify another frame rate based on your business requirements.
const newVideoTrack = newStream.getVideoTracks()[0];
// Call streamInfo.updateVideoTrack to replace the video track.
streamInfo.updateVideoTrack(newVideoTrack);
} else if (this.requestId) {
// If requestAnimationFrame was configured and no video track exists, cancel drawing.
cancelAnimationFrame(this.requestId);
}
return Promise.resolve();
}
}