-
Notifications
You must be signed in to change notification settings - Fork 9
/
filterTask.js
39 lines (36 loc) · 1.01 KB
/
filterTask.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
module.exports = function filterTask(videoElement, canvas, selectedFilter) {
let tmpCanvas;
let tmpCtx;
let ctx;
let stopped = false;
// Draws a frame on the specified canvas after applying the selected filter every
// requestAnimationFrame
const drawFrame = function drawFrame() {
if (!ctx) {
ctx = canvas.getContext('2d');
}
if (!tmpCanvas) {
tmpCanvas = document.createElement('canvas');
tmpCtx = tmpCanvas.getContext('2d');
}
tmpCanvas.width = canvas.width;
tmpCanvas.height = canvas.height;
tmpCtx.drawImage(videoElement, 0, 0, tmpCanvas.width, tmpCanvas.height);
const imgData = tmpCtx.getImageData(0, 0, tmpCanvas.width, tmpCanvas.height);
const data = selectedFilter(imgData);
ctx.putImageData(data, 0, 0);
if (!stopped) {
requestAnimationFrame(drawFrame);
} else {
tmpCanvas = null;
tmpCtx = null;
ctx = null;
}
};
requestAnimationFrame(drawFrame);
return {
stop: () => {
stopped = true;
},
};
};