refactor(capture): expose an Event Emitter API

This commit is contained in:
wryk 2019-03-15 19:25:36 +01:00
parent 21eaa1bda7
commit 3a2c80a2a5
2 changed files with 28 additions and 18 deletions

View file

@ -1,16 +1,22 @@
import { import EventEmitter from 'eventemitter3'
GIF_WIDTH,
GIF_HEIGHT,
GIF_FRAME_RATE
} from '/constants.js'
import { import {
makeRectangle, makeRectangle,
crop crop
} from '/services/rectangle.js' } from '/services/rectangle.js'
export function capture (commit, mediaStream, duration) { import {
return new Promise((resolve, reject) => { GIF_WIDTH,
GIF_HEIGHT,
GIF_FRAME_RATE
} from '/constants.js'
export function capture (mediaStream, duration) {
const emitter = new EventEmitter()
Promise.resolve().then(() => {
const video = document.createElement('video') const video = document.createElement('video')
video.autoplay = true video.autoplay = true
video.setAttribute('playsinline', '') video.setAttribute('playsinline', '')
@ -40,8 +46,6 @@ export function capture (commit, mediaStream, duration) {
const intervalId = setInterval(() => { const intervalId = setInterval(() => {
if (imageDataList.length < totalFrames) { if (imageDataList.length < totalFrames) {
console.log(`Capturing frame ${imageDataList.length + 1} / ${totalFrames}`)
canvasContext.drawImage( canvasContext.drawImage(
video, video,
soureRectangle.x, soureRectangle.x,
@ -63,11 +67,11 @@ export function capture (commit, mediaStream, duration) {
imageDataList.push(imageData) imageDataList.push(imageData)
commit('updateCaptureState', imageDataList.length / totalFrames * 100) emitter.emit('progress', imageDataList.length / totalFrames)
} else { } else {
clearInterval(intervalId) clearInterval(intervalId)
resolve({ emitter.emit('done', {
imageDataList, imageDataList,
imageWidth: GIF_WIDTH, imageWidth: GIF_WIDTH,
imageHeight: GIF_HEIGHT, imageHeight: GIF_HEIGHT,
@ -77,4 +81,7 @@ export function capture (commit, mediaStream, duration) {
}, delayTime) }, delayTime)
}) })
}) })
.catch(error => emitter.emit('error', error))
return emitter;
} }

View file

@ -111,14 +111,17 @@ export default new Vuex.Store({
}, },
capture ({ commit, dispatch, state }) { capture ({ commit, dispatch, state }) {
commit('startCapture') commit('startCapture')
const capturing = capture(state.mediaStream, state.timer.selected * 1000)
capture(commit, state.mediaStream, state.timer.selected * 1000) capturing.once('error', error => console.error(error))
.then(captureData => {
capturing.on('progress', value => commit('updateCaptureState', Math.round(value * 100)))
capturing.once('done', captureData => {
commit('stopCapture') commit('stopCapture')
commit('updateCaptureState', 0) commit('updateCaptureState', 0)
dispatch('encode', captureData) dispatch('encode', captureData)
}) })
.catch(error => console.error(error))
}, },
encode ({ commit }, captureData) { encode ({ commit }, captureData) {
commit('startEncoding') commit('startEncoding')