diff --git a/README.md b/README.md index 6cb97e5..b2a82e1 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,8 @@ A small pixel art drawing app that runs in your web browser. Everything lives in - **Eraser**: click the Eraser button, then click or drag to erase. Clicking with the right mouse button also erases. Click **Brush** to go back to painting. - **Grid lines**: turns the faint lines between squares on or off. - **Clear**: wipes the whole drawing. It asks you first, just in case. +- **Save PNG**: downloads your drawing as a picture file called `pixel-art.png` (512×512, each square becomes a crisp 16×16 block). Empty squares are see-through in the saved picture. Grid lines are not included. It also works with touch screens and drawing pens. -Note: the drawing isn't saved. Refreshing or closing the page starts you with a blank grid. +Note: the drawing isn't kept by the page itself. Use **Save PNG** if you want to keep it, because refreshing or closing the page starts you with a blank grid. diff --git a/index.html b/index.html index 8230560..2f3e553 100644 --- a/index.html +++ b/index.html @@ -130,6 +130,7 @@ +
@@ -158,6 +159,7 @@ const eraserBtn = document.getElementById("eraserBtn"); const linesBtn = document.getElementById("linesBtn"); const clearBtn = document.getElementById("clearBtn"); + const saveBtn = document.getElementById("saveBtn"); let color = COLORS[0]; let erasing = false; @@ -256,6 +258,43 @@ } }); + // Save the drawing as a PNG image. Each square becomes a block of + // EXPORT_SCALE x EXPORT_SCALE pixels so the picture isn't tiny. + // Empty (erased) squares are saved as transparent. + const EXPORT_SCALE = 16; + saveBtn.addEventListener("click", function () { + const canvas = document.createElement("canvas"); + canvas.width = SIZE * EXPORT_SCALE; + canvas.height = SIZE * EXPORT_SCALE; + const ctx = canvas.getContext("2d"); + cells.forEach(function (cell, i) { + const c = cell.style.backgroundColor; + if (!c) return; + ctx.fillStyle = c; + ctx.fillRect((i % SIZE) * EXPORT_SCALE, Math.floor(i / SIZE) * EXPORT_SCALE, + EXPORT_SCALE, EXPORT_SCALE); + }); + + const fileName = "pixel-art.png"; + function download(href, revoke) { + const a = document.createElement("a"); + a.href = href; + a.download = fileName; + document.body.appendChild(a); + a.click(); + a.remove(); + if (revoke) setTimeout(function () { URL.revokeObjectURL(href); }, 1000); + } + if (canvas.toBlob) { + canvas.toBlob(function (blob) { + if (blob) download(URL.createObjectURL(blob), true); + else download(canvas.toDataURL("image/png"), false); + }, "image/png"); + } else { + download(canvas.toDataURL("image/png"), false); + } + }); + linesBtn.classList.add("active"); updateUI(); })();