-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
101 lines (85 loc) · 2.5 KB
/
main.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
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
var iter = 0;
/**
* Gets file input from element #file at HTML
* Uses FileReader to read that file ArrayBuffer when the file's read'n loaded.
* Finally, converts that arrayBuffer to a Byte array and sends it to chip to be loaded.
*/
function loadFile(){
const file = document.getElementById('file').files[0];
const reader = new FileReader();
reader.onload = function () {
const arrayBuffer = reader.result;
const bArray = new Uint8Array(arrayBuffer);
chip.loadProgram(bArray);
setInterval(start, 1/30);
}
reader.readAsArrayBuffer(file);
}
function fitToContainer(canvas){
// Make it visually fill the positioned parent
canvas.style.width ='100%';
canvas.style.height='100%';
// ...then set the internal size to match
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
}
/**
* Get the display from the chip and loops it to check the pixels and paint it.
*/
function redrawCanvas(){
/**
* Draws a pixel filling a lil rect of size of canvas in relation with console display size at {x, y}
* @param coor
* @param color
*/
const drawPixel = (coor, color) => {
const { x, y } = coor;
ctx
ctx.fillStyle = color;
ctx.fillRect(x * PIXEL_WIDTH, y * PIXEL_HEIGHT, PIXEL_WIDTH, PIXEL_HEIGHT);
}
const { display } = chip;
display.forEach( (pixel, index) => {
const coor = {
x: index % 64,
y: parseInt(index / 64)
};
drawPixel(coor, ( pixel == 1 ) ? "green" : "black");
})
chip.removeDrawFlag();
}
function start(){
if(chip) {
if(chip.needsRedraw) {
redrawCanvas();
}
chip.setKeyBuffer(keyboard.getKeyBuffer());
chip.run();
}
}
function addListeners(){
const getKey = keyCode => String.fromCharCode(keyCode);
document.addEventListener('keydown', event => {
keyboard.keyPressed(getKey(event.keyCode));
} );
document.addEventListener('keyup', event => {
keyboard.keyReleased(getKey(event.keyCode));
} );
}
function initEmulator(){
//Fullscreen canvas
redrawCanvas();
addListeners();
}
//Getting canvas
const canvas = document.getElementById("canvas");
fitToContainer(canvas);
//Useful constants
const PIXEL_WIDTH = canvas.width / 64;
const PIXEL_HEIGHT = canvas.height / 32;
//Getting context
const ctx = canvas.getContext('2d');
//Init chip
let chip = new Chip();
const keyboard = new Keyboard(chip);
initEmulator()