File size: 2,253 Bytes
e5ae926
 
 
 
 
 
 
 
 
 
 
c976217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5ae926
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d85080
e5ae926
 
c976217
e5ae926
 
 
 
c976217
e5ae926
 
 
 
 
 
 
 
 
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
102
103
104
105
106
107
108
const canvas = document.querySelector("#canvas");

function handleResize() {
	requestAnimationFrame(() => {
		canvas.width = window.innerWidth;
		canvas.height = window.innerHeight;
	});
}
handleResize();
window.addEventListener("resize", handleResize, { passive: true });

function createGameLoop(callback) {
    let lastTimestamp;

    function gameLoop(timestamp) {
        if (lastTimestamp) {
            const delta = timestamp - lastTimestamp;

            if (delta >= 1000 / 60) {
                lastTimestamp = timestamp;
                callback(delta);
            }
        } else {
            lastTimestamp = timestamp;
        }
        requestAnimationFrame(gameLoop);
    }

    return gameLoop;
}

function downloadCanvasImage() {
    // Get the canvas element
    const canvas = document.getElementById('canvas');

    // Create a new 'a' element
    let link = document.createElement('a');

    // Set the download attribute with a file name
    link.download = 'canvas_image.png';

    // Get the data URL for the canvas
    link.href = canvas.toDataURL();

    // Trigger the click event on the link
    link.click();
}


const clients = {
	host: "__ESDEKA::host__",
	guest: "__ESDEKA::guest__",
};

// Shared communicators

function subscribe(channel, callback) {
	function handleMessage(event) {
		if (
			event.data.client &&
			Object.values(clients).includes(event.data.client) &&
			event.data.channel === channel
		) {
			callback(event);
		}
	}
	window.addEventListener("message", handleMessage);

	return () => {
		window.removeEventListener("message", handleMessage);
	};
}
const host = {};
// Guest communicators

function answer(window_, channel, targetOrigin = "*") {
	window_.postMessage(
		{
			client: clients.guest,
			channel,
			action: {
				type: "answer",
			},
		},
		targetOrigin
	);
}

function handleTemplate(template) {
	Function("Template", `${template}`)();
}

subscribe("2DGameCreator", event => {
	const { action } = event.data;
	switch (action.type) {
		case "call":
			host.current = event.source;
			answer(event.source, "2DGameCreator");
			handleTemplate(action.payload.template);
			break;
		case "broadcast":
			handleTemplate(action.payload.template);
			break;
		default:
			break;
	}
});