about summary refs log tree commit diff stats
path: root/js/dither-video/video.js
blob: 0da01579482ab5c8ddc327abed0c43278d39e974 (plain) (blame)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const toggleCameraButton = document.getElementById('toggleCamera');
const video = document.getElementById('webcam');
const canvas = document.getElementById('ditheredOutput');
const context = canvas.getContext('2d');

let stream = null;
let isCameraOn = false;

// FIXME: Sort out how to crop the image rather than squish and distort it.
const lowResWidth = 160; // Gameboy camera resolution: 160×144
const lowResHeight = 120; // If I use the GB camera resolution the image gets distorted

toggleCameraButton.addEventListener('click', async () => {
    if (!isCameraOn) {
        try {
            stream = await navigator.mediaDevices.getUserMedia({ video: true });
            video.srcObject = stream;
            video.style.display = 'block';
            isCameraOn = true;
            toggleCameraButton.textContent = 'Turn Camera Off';
            video.addEventListener('loadeddata', () => {
                canvas.width = lowResWidth;
                canvas.height = lowResHeight;
                requestAnimationFrame(processFrame);
            });
        } catch (err) {
            console.error('Failed to access the camera: ', err);
        }
    } else {
        stream.getTracks().forEach(track => track.stop());
        video.style.display = 'none';
        isCameraOn = false;
        toggleCameraButton.textContent = 'Turn Camera On';
    }
});

function processFrame() {
    if (!isCameraOn) return;

    context.drawImage(video, 0, 0, lowResWidth, lowResHeight);
    const frame = context.getImageData(0, 0, lowResWidth, lowResHeight);
    applyFloydSteinbergDithering(frame);
    context.putImageData(frame, 0, 0);
    requestAnimationFrame(processFrame);
}


function applyFloydSteinbergDithering(imageData) {
    const { data, width, height } = imageData;

    // Helpers to access and set pixel values
    const getPixelIndex = (x, y) => (y * width + x) * 4;
    const getPixelValue = (x, y) => data[getPixelIndex(x, y)];
    const setPixelValue = (x, y, value) => {
        const index = getPixelIndex(x, y);
        data[index] = value;
        data[index + 1] = value;
        data[index + 2] = value;
    };

    // Helper that clamps a value between 0 and 255
    const clamp = (value) => Math.max(0, Math.min(255, value));

    // Process a single pixel
    const processPixel = (x, y) => {
        const oldPixel = getPixelValue(x, y);
        const newPixel = oldPixel < 128 ? 0 : 255; // Threshold of the pixel value
        setPixelValue(x, y, newPixel);
        const quantError = oldPixel - newPixel;

        // Spreads the error to neighboring pixels
        if (x + 1 < width) {
            const idx = getPixelIndex(x + 1, y);
            data[idx] = clamp(data[idx] + quantError * 7 / 16);
        }
        if (x - 1 >= 0 && y + 1 < height) {
            const idx = getPixelIndex(x - 1, y + 1);
            data[idx] = clamp(data[idx] + quantError * 3 / 16);
        }
        if (y + 1 < height) {
            const idx = getPixelIndex(x, y + 1);
            data[idx] = clamp(data[idx] + quantError * 5 / 16);
        }
        if (x + 1 < width && y + 1 < height) {
            const idx = getPixelIndex(x + 1, y + 1);
            data[idx] = clamp(data[idx] + quantError * 1 / 16);
        }
    };

    // TODO: This seems like a mad inefficient way to do this, but it does work. Noodle on if it is worth making this more efficient.
    // Process all of the pixels
    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            processPixel(x, y);
        }
    }
}

function clamp(value) {
    return Math.max(0, Math.min(255, value));
}