UNPKG

@cloudroom/electron-rtcsdk

Version:

这是一款在线音视频SDK插件,您可以从README.md中获取演示demo

97 lines (91 loc) 3.13 kB
const EventEmitter = require('events').EventEmitter; const YUVBuffer = require('yuv-buffer'); const YUVCanvas = require('yuv-canvas'); class Renderer { constructor() { this.cacheCanvasOpts = {}; this.yuv = {}; this.event = new EventEmitter(); this.ready = false; this.scaleType = 0; this.container = {}; this.canvas = {}; this.element = {}; } bind(element) { this.element = element; let container = document.createElement('div'); Object.assign(container.style, { width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', overflow: 'hidden', position: 'replative', }); this.container = container; element.appendChild(this.container); this.canvas = document.createElement('canvas'); this.container.appendChild(this.canvas); this.yuv = YUVCanvas.attach(this.canvas, { webGL: false }); } unbind() { this.container && this.container.removeChild(this.canvas); this.element && this.element.removeChild(this.container); this.yuv = null; this.element = null; this.canvas = null; this.view = null; } updateCanvas(options = { width: 0, height: 0, scaleType: 0, clientWidth: 0, clientHeight: 0, }) { this.cacheCanvasOpts = Object.assign({}, options); this.canvas.width = options.width; this.canvas.height = options.height; this.canvas.style.width = "100%"; this.canvas.style.height = "100%"; if (this.scaleType === 1) { this.canvas.style.objectFit = "cover"; } else if (this.scaleType === 2) { this.canvas.style.objectFit = "fill"; } else { this.canvas.style.objectFit = "contain"; } } drawFrame(imageData) { if (!this.ready) { this.ready = true; this.event.emit('ready'); } const { yUint8Array, uUint8Array, vUint8Array, width, height } = imageData; this.updateCanvas({ width, height, scaleType: this.scaleType, clientWidth: this.container.clientWidth, clientHeight: this.container.clientHeight, }); const halfWidth = width / 2, halfHeight = height / 2; let format = YUVBuffer.format({ width, height, chromaWidth: halfWidth, chromaHeight: halfHeight }); let y = YUVBuffer.lumaPlane(format, yUint8Array, width); let u = YUVBuffer.chromaPlane(format, uUint8Array, halfWidth); let v = YUVBuffer.chromaPlane(format, vUint8Array, halfWidth); let frame = YUVBuffer.frame(format, y, u, v); this.yuv.drawFrame(frame); } setScaleType(mode = 0) { this.scaleType = mode; } } exports.default = Renderer;