Created
January 14, 2022 02:51
-
-
Save guzmonne/f9c81b4cdd9b05b1a0f593f85e28582c to your computer and use it in GitHub Desktop.
WindowsJS PNG exporter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.title = "Hello!"; | |
window.visible = true; | |
const monotonicDelta = createMonotonicFPSGenerator(60); | |
function requestMonotonicAnimationFrame(callback) { | |
callback(monotonicDelta.next().value); | |
} | |
const canvas = window.canvas; | |
const generator = createLeftPaddedNumberGenerator(6, 0); | |
async function draw(delta = 0) { | |
const cyan = "#023047"; | |
const red = "#eb005a"; | |
const orange = "darkorange"; | |
canvas.fillStyle = cyan; | |
canvas.fillRect(0, 0, canvas.width, canvas.height); | |
canvas.fillStyle = orange; | |
const y = canvas.height / 2; | |
const w = canvas.width; | |
const t = Math.cos(delta / 300); | |
const x = w / 2 + (w / 4) * t; | |
canvas.save(); | |
canvas.translate(x, y); | |
canvas.rotate((t * Math.PI) / 2); | |
canvas.fillRect(-100, -100, 200, 200); | |
canvas.restore(); | |
const screenshot = await canvas.encode(); | |
const filepath = File.cwd + "/" + generator.next().value + ".png"; | |
await File.write(filepath, screenshot); | |
requestMonotonicAnimationFrame(draw); | |
} | |
// Start the animation. | |
requestMonotonicAnimationFrame(draw); | |
// Helper functions | |
/** | |
* Creates a generator capable of delivering a time that increments monotonically using the `fps` | |
* ellapsed time as discrete step. | |
* | |
* @example | |
* ```javascript | |
* const generator = createMonotonicFPSGenerator(60); | |
* console.log(generator.next().value); | |
* // 0 | |
* console.log(generator.next().value); | |
* // 16.66667 | |
* ``` | |
* | |
* @param {number} fps - Frames per seconds needed to calculat the frame execution time. | |
* @param {number} start - Time from which to start the generator. | |
*/ | |
function* createMonotonicFPSGenerator(fps = 60, start = 0) { | |
const step = 1000 / fps; | |
while (true) { | |
yield start; | |
start += step; | |
} | |
} | |
/** | |
* Creates a left padded number generator left padded to always have a length equal to `length`. | |
* | |
* @example | |
* ```javascript | |
* const generator = createLeftPaddedNumberGenerator(3, 0); | |
* console.log(generator.next().value); | |
* // 000 | |
* console.log(generator.nex().value); | |
* // 001 | |
* ``` | |
* | |
* @param {number} length - Fix length of the returning string. | |
* @param {number} start - Start number fo the generator. | |
*/ | |
function* createLeftPaddedNumberGenerator(length = 6, start = 0) { | |
while (true) { | |
yield String(start++).padStart(length, "0"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment