Learn RxJS
Search…
Matrix Digital Rain
By adamlubek
This recipe demonstrates RxJS implementation of Matrix Digital Rain.

Example Code

Could not load image
Matrix Digital Rain

index.ts

1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { scan } from 'rxjs/operators';
4
import { render } from './html-renderer';
5
import { markForRemoval, updateDrops, updateMatrix } from './matrix';
6
7
interval(300)
8
.pipe(
9
scan<number, any[]>(matrix => (
10
markForRemoval(matrix),
11
updateDrops(matrix),
12
updateMatrix(matrix)
13
), [])
14
).subscribe(render);
Copied!

matrix.ts

1
const drop = (x: number, y: number) => ({ x, y, d: [], remove: false });
2
const random = (max: number) => Math.floor(Math.random() * Math.floor(max));
3
const ranodmChar = () => String.fromCharCode(random(128));
4
5
export const markForRemoval = matrix =>
6
matrix.forEach(
7
drop => (drop.remove = drop.remove ? true : drop.d.length > 20)
8
);
9
export const updateDrops = matrix =>
10
matrix.forEach(
11
drop =>
12
(drop.d = drop.remove
13
? drop.d.slice(1).map(e => ranodmChar())
14
: [ranodmChar(), ...drop.d.map(e => ranodmChar())])
15
);
16
export const updateMatrix = matrix => [
17
...matrix,
18
drop(random(window.innerHeight) / 4, random(window.innerWidth))
19
];
Copied!

html-renderer.ts

1
const createElem = drop => {
2
const elem = document.createElement('div');
3
elem.style.position = 'absolute';
4
elem.style.marginTop = drop.x + 'px';
5
elem.style.marginLeft = drop.y + 'px';
6
elem.style.fontSize = '12px';
7
elem.innerHTML = drop.d.reduce((acc, c) => (acc += '<br/>' + c), '');
8
elem.style['color'] = `rgb(21, ${100 + drop.d.length * 10}, 21)`;
9
return elem;
10
};
11
12
export const render = matrix => {
13
document.body.innerHTML = '';
14
const container = document.createElement('div');
15
container.style.position = 'relative';
16
matrix.forEach(m => container.appendChild(createElem(m)));
17
document.body.appendChild(container);
18
};
Copied!

Operators Used

Last modified 1yr ago