var lastTime = new Date().getTime(); var canvas = document.getElementById("viewer"); var context = canvas.getContext("2d"); var atlas = new SpriteAtlas("./assets/", "sprites.xml"); var currentStage; var lastFailedId = "void"; let stages = []; let sets = []; let setsLoaded = []; stages.push({ id: "empty", setup: () => { }, update: (delta) => { }, draw: (context, delta) => { }, cleanup: () => { }, }); currentStage = stages[0]; atlas.load().then(() => { resize(); currentStage.setup(); raf(); }).catch(e => console.error(e)); function raf() { let currentTime = new Date().getTime(); let delta = (currentTime - lastTime) / 10; context.height = context.height; context.clearRect(0, 0, canvas.width, canvas.height); context.save(); context.translate(0.5, 0.5); viewerUpdate(delta); viewerDraw(context, delta); context.restore(); window.requestAnimationFrame(() => raf()); lastTime = currentTime; }; window.addEventListener('resize', resize); function resize(event) { let dpi = window.devicePixelRatio; canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; context.width = canvas.clientWidth / dpi; context.height = canvas.clientHeight / dpi; context.webkitImageSmoothingEnabled = true; context.imageSmoothingEnabled = true; } function viewerUpdate(delta) { center = { x: canvas.width / 2, y: canvas.height / 2 }; currentStage.update(delta); } function viewerDraw(context, delta) { context.save(); context.translate(center.x, center.y); currentStage.draw(context, delta); context.restore(); } function play(id) { if (currentStage && currentStage.id == id) { return; } if (currentStage) { currentStage.cleanup(); } currentStage = stages.find(stage => stage.id == id); if (!currentStage) { lastFailedId = id; play("void"); return; } currentStage.setup(); } function getSet(setId) { let found = sets.find(set => set.id == setId); if(!found) { throw new Error("Set not found:", setId); } return found; }