伺服器上先準備好 jpeg 格式檔: mjpeg0, mjpeg1, mjpeg2 ... 等, 再寫一個 mjpeg.html 及一個 mpeg.js 檔案, mjpeg.html 範例:
<html><head><meta charset='utf-8'></head>
<body> <script type='application/javascript' src='mjpeg.js'></script></body>
</html>
底下是一個 Javascript 檔案 mjpeg.js 範例程式, 全部放到 http 伺服器同 jpeg 檔案的附錄內, 讓它執行, 用瀏覽下抓上述 mjpeg.htm, 就會定時從伺服器下載 jpeg 檔, 再繪製貼圖到 canvas, 這就是一個超簡單又名符其實的 motion jpeg 伺服器:
class MjpegViewer {
constructor(fps, width, height) {
this._fps = fps;
this._running = false;
this._canvas = document.createElement('canvas');
this._canvas.width = width;
this._canvas.height = height;
this._canvas.style.setProperty('border', '1px solid #000000');
document.body.append(this._canvas);
}
get _duration( ){ return 0 < this._fps && this._fps < 32 ? 1000/this._fps : 100 }
get _context( ) { return this._canvas.getContext('2d') }
get stop( ) { this._running = false }
set host(_ip) {
var _counter = 0;
this._running = true;
const _period = this._duration;
const _draw = (img)=> { this._context.drawImage(img, 0, 0) }
const _periodRun = ( )=> {
if(! this._running) return;
const _img = document.createElement('img');
_img.onerror = ( )=> { _img.remove( ) }
_img.onload = (_)=> {
_counter ++;
_draw(_.target);
_img.remove();
};
_img.src = _ip + '/mjpeg' + (_counter);
setTimeout(_periodRun, _period);
};
_periodRun( ); // fire the process
}
};
const viewer = new MjpegViewer(1, 1024, 768) // fps = 1 frame/sec, canvas: 1024x768
viewer.host = 'http://192.168.0.1:8080';
setTimeout( ( )=>{ viewer.stop } , 10000);
沒有留言:
張貼留言