-
Notifications
You must be signed in to change notification settings - Fork 399
/
Copy pathcanvas-image-processing.js
53 lines (42 loc) · 1.44 KB
/
canvas-image-processing.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* A Canvas2D example of async loading and image processing.
* @author Matt DesLauriers (@mattdesl)
*/
const canvasSketch = require('canvas-sketch');
const load = require('load-asset');
canvasSketch(async ({ update }) => {
const image = await load('assets/baboon.jpg');
// Update our sketch with new settings
update({
dimensions: [ image.width, image.height ]
});
// Render our sketch
return ({ context, width, height }) => {
// Render to canvas
context.drawImage(image, 0, 0, width, height);
// Extract bitmap pixel data
const pixels = context.getImageData(0, 0, width, height);
// Manipulate pixels
const data = pixels.data;
let len = width;
while (len) {
const newX = Math.floor(Math.random() * len--);
const oldX = len;
// Sometimes leave row in tact
if (Math.random() > 0.85) continue;
for (let y = 0; y < height; y++) {
// Sometimes leave column in tact
if (Math.random() > 0.925) continue;
// Copy new random column into old column
const newIndex = newX + y * width;
const oldIndex = oldX + y * width;
// Make 'grayscale' by just copying blue channel
data[oldIndex * 4 + 0] = data[newIndex * 4 + 2];
data[oldIndex * 4 + 1] = data[newIndex * 4 + 2];
data[oldIndex * 4 + 2] = data[newIndex * 4 + 2];
}
}
// Put new pixels back into canvas
context.putImageData(pixels, 0, 0);
};
});