From 4a0a9d10d39f1b7291c3bd1d214cf044cbfb2586 Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Mon, 20 Jul 2020 00:18:06 +0100 Subject: [PATCH] download button (not tested yet) --- index.pug | 3 +-- script.js | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/index.pug b/index.pug index 14f7a48..adffd5d 100644 --- a/index.pug +++ b/index.pug @@ -30,8 +30,7 @@ html(lang="en-gb") h2 download textarea#output br - //- - button#download download + button#download download button.pagination.prev#add add another image button.pagination.start#reset start again script(type="module") diff --git a/script.js b/script.js index f2f90e1..ea37bda 100644 --- a/script.js +++ b/script.js @@ -1,5 +1,17 @@ import init, {load_default_game_data, add_tiles} from './pkg/bitsy_tiles.js'; +// stolen from https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server +function download(filename, text) { + let element = document.createElement('a'); + + element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); + element.setAttribute('download', filename); + element.style.display = 'none'; + document.body.appendChild(element); + element.click(); + document.body.removeChild(element); +} + function el(id) { return document.getElementById(id); } @@ -35,6 +47,7 @@ async function run() { await init(); const buttonAddImage = el("add"); + const buttonDownload = el("download"); const buttonGameDataProceed = el("game-data-next"); const textareaGameDataInput = el("game-data"); const buttonImportGame = el("import"); @@ -110,6 +123,13 @@ async function run() { buttonImportGame.addEventListener("click", addTiles); buttonImportGame.addEventListener("touchend", addTiles); + function handleDownload() { + download("output.bitsy", textareaGameDataOutput.value); + } + + buttonDownload.addEventListener("click", handleDownload); + buttonDownload.addEventListener("touchend", handleDownload); + function addImage() { textareaGameDataInput.value = textareaGameDataOutput.value; textareaGameDataOutput.value = "";