tav-media
Version:
Cross platform media editing framework
53 lines (52 loc) • 1.64 kB
JavaScript
import { DEFAULT_CANVAS_SIZE, WEBGL_CONTEXT_ATTRIBUTES } from '../constant';
import { BackendContext } from './backend-context';
export class GlobalCanvas {
constructor() {
this._canvas = null;
this._glContext = null;
this.width = DEFAULT_CANVAS_SIZE;
this.height = DEFAULT_CANVAS_SIZE;
this.retainCount = 0;
}
retain() {
if (this.retainCount === 0) {
try {
this._canvas = new OffscreenCanvas(0, 0);
}
catch (error) {
this._canvas = document.createElement('canvas');
}
this._canvas.width = this.width;
this._canvas.height = this.height;
const gl = this._canvas.getContext('webgl', WEBGL_CONTEXT_ATTRIBUTES);
if (!gl)
throw new Error('Canvas context is not WebGL!');
this._glContext = BackendContext.from(gl);
}
this.retainCount += 1;
}
release() {
this.retainCount -= 1;
if (this.retainCount === 0) {
if (!this._glContext)
return;
this._glContext.destroy();
this._glContext = null;
this._canvas = null;
}
}
get canvas() {
return this._canvas;
}
get glContext() {
return this._glContext;
}
setCanvasSize(width = DEFAULT_CANVAS_SIZE, height = DEFAULT_CANVAS_SIZE) {
this.width = width;
this.height = height;
if (this._glContext && this._canvas) {
this._canvas.width = width;
this._canvas.height = height;
}
}
}