-
Notifications
You must be signed in to change notification settings - Fork 0
/
drawingUtils.js.new
63 lines (49 loc) · 1.65 KB
/
drawingUtils.js.new
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
let g_canvas;
let g_context;
let g_color = [0,0,0,255];
let g_factorX = 1;
let g_factorY = 1;
// to increase performance createImageData method
// should be executed once e.g. during initialization
let g_image;
let g_data;
export let iWidth = 800;
export let iHeight = 600;
function toHexString(cc) {
return "#" + cc.r.toString(16) + cc.g.toString(16) + cc.b.toString(16) + cc.a.toString(16);
}
export function init() {
g_canvas = document.querySelector('#my-canvas');
g_context = g_canvas.getContext('2d');
function resizeCanvas() {
g_factorX = g_canvas.width / iWidth;
g_factorY = g_canvas.height / iHeight;
// to increase performance createImageData method
// should be executed once e.g. during initialization
g_image = g_context.createImageData(g_canvas.width, g_canvas.height);
g_data = g_image.data;
}
addEventListener("resize", (event) => {resizeCanvas();});
resizeCanvas();
// g_context.save(); //Freeze redraw
}
export function drawPixel(x, y, color = undefined) {
if (color != undefined) {
g_color = color;
g_context.fillStyle = toHexString(color);
}
x*=g_factorX;
y*=g_factorY;
// g_context.fillRect(x, y, 1, 1);
var roundedX = Math.round(x);
var roundedY = Math.round(y);
var index = 4 * (g_canvas.width * roundedY + roundedX);
g_data[index + 0] = g_color.r;
g_data[index + 1] = g_color.g;
g_data[index + 2] = g_color.b;
g_data[index + 3] = g_color.a;
}
export function swapBuffer() {
// g_context.restore(); //And now do the redraw
g_context.putImageData(g_image, 0, 0);
}