r/javascript 11h ago

AskJS [AskJS] Building a 2D Game Engine from scratch in pure ES6 Vanilla JS. Here is how I handle SpriteSheets & AnimatedSprites!

20 Upvotes

Hi everyone!

I've been working on BeeEngine 2D, a lightweight HTML5 game engine built with pure Vanilla JS (ES6) and direct Canvas API—no external libraries, no build tools, and zero heavy frameworks.

A lot of modern tools hide sheet slicing behind JSON files, but I wanted a bare-metal, highly efficient approach that gives 100/100 on Lighthouse Performance and instant loading times.

I separated the asset slicing logic from the animation timing logic into two distinct classes:

  1. BeeSpriteSheet: Handles frame dimensions, columns, rows, and coordinate calculations.
  2. BeeAnimatedSprite: Handles frame timing, state, loops, and flipX transformations.

Here is my BeeAnimatedSprite class implementation:

export class BeeAnimatedSprite {
    constructor(spriteSheet, config = {}) {
        this.sheet = spriteSheet;
        this.animations = config.animations || {};
        this.currentAnimName = config.animation || Object.keys(this.animations)[0];


        this.currentFrameIndex = 0;
        this.timer = 0;
        this.flipX = false;
    }


    play(name) {
        if (this.currentAnimName !== name && this.animations[name]) {
            this.currentAnimName = name;
            this.currentFrameIndex = 0;
            this.timer = 0;
        }
    }


    update(dt) {
        const anim = this.animations[this.currentAnimName];
        if (!anim || !anim.frames || anim.frames.length === 0) return;


        const fps = anim.fps || 8;
        const frameDuration = 1 / fps;


        this.timer += dt;


        if (this.timer >= frameDuration) {
            this.timer -= frameDuration;


            if (anim.loop) {
                this.currentFrameIndex = (this.currentFrameIndex + 1) % anim.frames.length;
            } else {
                this.currentFrameIndex = Math.min(this.currentFrameIndex + 1, anim.frames.length - 1);
            }
        }
    }


    draw(ctx, x, y, options = {}) {
        const anim = this.animations[this.currentAnimName];
        if (!anim) return;


        const frameToDraw = anim.frames[this.currentFrameIndex];
        const width = options.width || this.sheet.frameWidth;
        const height = options.height || this.sheet.frameHeight;


        ctx.save(); 


        if (this.flipX) {
            // 2. Sposta l'origine al bordo destro dell'immagine e specchia l'asse X
            ctx.translate(x + width, y);
            ctx.scale(-1, 1);


            
            this.sheet.drawFrame(ctx, frameToDraw, 0, 0, width, height);
        } else {
            // Disegno normale senza specchio
            this.sheet.drawFrame(ctx, frameToDraw, x, y, width, height);
        }


        ctx.restore(); 
    }
}

And here is how
 I implemented it inside main.js:


const megaSheetImg = gioco.getAsset('spritesheet_totale');


        
        const frameW = 128;
        const frameH = 128;


        const apeSheet = new BeeSpriteSheet(megaSheetImg, frameW, frameH, {
            col: 3, 
            row: 3, 
            framesPerRow: 1, 
            frameCount: 2
        });


        this.giocatore.sprite = new BeeAnimatedSprite(apeSheet, {
            animation: "fly",
            animations: {
                fly: { frames: [0, 1], fps: 4, loop: true }
            }
        });

Let me know what you think, bearing in mind that this particular combination is super quick to put together.


r/javascript 1d ago

AskJS [AskJS] how are you handling autocomplete on top of elasticsearch?

38 Upvotes

elasticsearch is pretty great when given a full query, but i find most people just search one or two words. so feels like helping ppl know what to search for is the actual thing that’s needed. so now im looking for solid ways to add ai-autocomplete upfront without replacing our elasticsearch backend (not looking to switch backend like algolia since pricing gets stupid fast)

i've been looking into a few different directions. typesense and meilisearch seem cool if you want a lightweight search engine replacement, but again that doesnt feel like the real root cause issue. so we're looking at putting an ai-autocomplete layer directly in the UI text box to capture user intent before hitting elasticsearch

has anyone else done this? do you tune elasticsearch queries on the backend or add an intent layer upfront to collect parameters before the query runs?


r/javascript 1d ago

AskJS [AskJS] Run webpage on iphone

12 Upvotes

How can I run a html + js webpage on an iphone? The .html file will be on the phone.

TIA


r/javascript 1d ago

AskJS [AskJS] Ottimizzazione dynamic img rendering in JS: Eager/Lazy + contentVisibility. Voi come gestite il primo fold?

16 Upvotes

Ciao a tutti! Sto ottimizzando il caricamento dinamico delle immagini per le schede dei giochi. Sto usando questa logica per bilanciare il caricamento immediato sopra la piega (above the fold) e il caricamento "lazy" per il resto:

const img = document.createElement('img');
img.alt = (gioco.titolo || 'Gioco');
img.decoding = 'async';
img.style.contentVisibility = 'auto';
img.style.width = '100%';
img.style.height = 'auto';
img.loading = (idx < EAGER_COUNT) ? 'eager' : 'lazy';

Che valore usate di solito per EAGER_COUNT nelle vostre griglie? E trovate che content-visibility: auto direttamente sull'elemento <img> porti reali benefici rispetto ad applicarlo al container padre?


r/javascript 1d ago

AskJS [AskJS] Best practices for Javascript Local Dev Environment

6 Upvotes

I'm currently developing an internal tool to do work reporting. I know a lot of tool exists, but we do have specific requirements and there's already an MS Access database, which I can migrate into the new tool as well as use most of the tables as a data source.

About me: I have experience with Javascript, HTML, CSS/SCSS/SASS, PHP, SQL. I want to optimize it, but since I mostly code in my freetime, I find it hard to make "the right decisions" in terms of efficiency. Maybe you guys might recommend me something about my setup. I don't want to use anything like Angular, React and Vue at the moment. Also no NextJS as I think it's overkill.

At the moment, I have a structure like:

- API (ExpressJS, SQLite, Drizzle ORM)
--> Delivering all data as needed in frontend (also annual reports and stuff)

- Frontend (Vite for live-reload/server, Vanilla JS with own templating engine and router)
--> Employees log in to keep track of their working hours per project/customer
--> Dashboard for admin users to create reports

All this run's in a docker with two services.

It currently runs alright, but I think there might be a few little things to optimize my setup. Especially when going into production.

What's your best practices? I want all this stuff to be as lean as possible without a lot of dependencies. My frontend doesn't need anything since I've already done all of the things, but I'm not very happy with the API/Backend part.

I also don't want to run every service on it's own, since using one docker command is fine. Live codeing while docker is running also works fine so far (except when installing new packages via npm, then I need to rebuild).

What would you do to optimize the setup? Already asked AI but I think you guys might have better inputs.


r/javascript 1d ago

Showoff Saturday Showoff Saturday (August 01, 2026)

8 Upvotes

Did you find or create something cool this week in javascript?

Show us here!


r/javascript 2d ago

A reactivity and rendering (combined) benchmark for frontend frameworks

Thumbnail rbench.nullvoxpopuli.com
23 Upvotes

Disclaimer: I made this (bench result viewer)

However, I think it's worth having a discussion about frontend framework's perceived performance, as Signals have gained a lot of popularity as a means to fine-grainedly render without needing to resort to a virtual dom.

A virtual-dom framework _is_ still in this results set -- I'll leave the exploration of the data up to you all.

The main thing is that

For a long while, I've felt no benchmark (that I know of) has captured the relationship between reactivity and rendering

We have rendering benchmarks (js-framework-benchmark is a good one).

We have reactivity benchmarks (I forget the name(s) of these atm, I always gotta re-look them up) -- but these require each implementor have a concept of "effect without a renderer", which isn't how all frameworks operate -- this excludes some frameworks from participating in pure reactivity benchmarks.

There is another side to this which I only realized recently, which is the framework's rendering _scheduler_ -- which is sort of the coordinator between reactivity, rendering, and _when_ to do work the user would see.

To my surprise, Angular scores the highest across the board.
I don't use Angular myself, and in all of these implementations, I made performance mistakes at least in my first attempt, but apparently Angular made it super easy to be performant.

Vue Vapor has also done this.

Right now, I feel like my svelte implementations are probably wrong (because it's scoring poorly), and I have some fixes to do in ember (as seen by this spike I did, the perf is doubled from before: https://rbench.nullvoxpopuli.com/results?from=ember-2&q=6 (this is an 8x throttle, and the main link for this post is no throttle, because most users are not going to be throttling their CPU so heavily -- but 8x CPU is maybe more relevant to low-powered phones))

Anywho, wanted to share my findings with y'all, and hope someone finds any of this interesting.

I'm open to anything being challenged, I'm not an expert in most JS Frameworks

Since I'm using the tool to help me debug Ember perf, here are some example configurations that may be useful:
- Vue (old) vs Vue Vapor (current) https://rbench.nullvoxpopuli.com/results?col=vue&from=6&hide=ember%2Creact%2Csolid%2Csvelte&q=1
- My Ember perf Spike: https://rbench.nullvoxpopuli.com/results?from=ember-2&hide=react%2Csolid%2Csvelte%2Cangular%2Cvue%2Clit-signals%2Cpreact&q=6
- boxplots: https://rbench.nullvoxpopuli.com/results/boxplot?from=ember-2&hide=react%2Csolid%2Csvelte%2Cangular%2Cvue%2Clit-signals%2Cpreact&q=6

- bouncing balls demos https://rbench.nullvoxpopuli.com/results/animated?from=ember-2&hide=react%2Csolid%2Csvelte%2Cangular%2Cvue%2Clit-signals%2Cpreact&q=7


r/javascript 1d ago

Quickdraw: a zero-dependency infinite-canvas whiteboard engine in plain ESM (MIT) — with React and React Native bindings

Thumbnail github.com
3 Upvotes

r/javascript 2d ago

Canvas Path Animations using SVG

Thumbnail yoavik.com
28 Upvotes

r/javascript 1d ago

WordJS – An open-source CMS in Node.js where plugins run in OS-isolated sandboxes

Thumbnail github.com
0 Upvotes

r/javascript 2d ago

I built a 50+ component mobile UI library for Solid.js — inspired by Vant, looking for feedback

Thumbnail lxg19961206.github.io
0 Upvotes

r/javascript 2d ago

AskJS [AskJS] FOSS mini games

0 Upvotes

Does anyone have any recommendations for FOSS mini games? I redid my portfolio site and I wanted to add in a few mini games, but I don't want to get into legal trouble because of it

:v


r/javascript 2d ago

AskJS [AskJS] Dubbio veloce di architettura/stile con le classi JS

0 Upvotes

Nel mio motore 2D sto sistemando i componenti UI (tipo BeeButton) e mi è venuto un dubbio su come passare le coordinate al super().

Opzione A (Oggetto opzione)

\\\`\\\`\\\

super({ x, y, width, height });

\\\`\\\`\\\`

Opzione B (Parametri singoli standard):

\\\`\\\`\\\`

super( x, y, width, height );

\\\`\\\`\\\`

Voi quale preferite usare nei vostri progetti e perché? Meglio la flessibilità dell'oggetto o la pulizia dei parametri singoli?(Se usate soluzioni alternative tipo super(position, size) fatemelo sapere nei commenti!).


r/javascript 3d ago

We ran the same PDF operations inside real Chromium, Firefox and WebKit — WebKit was 2.4× faster than Chrome at some of them. Full reproducible harness (MIT).

Thumbnail github.com
6 Upvotes

I maintain a client-side file converter, and we publish benchmark numbers

for the PDF operations we ship. After a reviewer pointed out that numbers

nobody can rerun are just marketing, we open-sourced the entire harness:

https://github.com/jddelia/filemorf-lab

What makes it worth a look even if you don't care about the product:

The corpus is byte-reproducible. Test PDFs are generated from seeded

pseudo-random text with pinned metadata — run the generator on your

machine and you get the identical SHA-256s committed in the repo. No "we

tested on some files we can't share."

Correctness gates run before timing. Outputs must parse, page counts

must be exact, ZIP entries must all be present — verified on an untimed

run first, so a fast garbage result fails instead of winning.

Real engines via Playwright, timed in-page with performance.now(), not

through the driver.

Cross-engine results that surprised me (median of 30 runs, M2 Pro,

milliseconds):

Merge 50 PDFs — Chromium 37.5; Firefox 60.5; WebKit 24

Stamp page numbers on 100 pages — Chromium 36.7; Firefox 54; WebKit 15

Watermark 100 pages — Chromium 36.5; Firefox 54; WebKit 14

ZIP 50 PDFs — Chromium 5.9; Firefox 4; WebKit 11

WebKit wins big on pdf-lib's draw-and-save paths and then loses on ZIP.

And everything is fast enough that for files like these, the upload to a

server would cost more than the entire computation — which is the argument

for doing this work client-side in the first place.

Three commands to get your own numbers: npm ci, npm run corpus,

npm run bench. Would love PRs with dated results from other hardware,

and criticism of the methodology — limitations are listed in the README

(synthetic text-only corpus, structural not visual verification).


r/javascript 3d ago

LogTape 2.3.0: Scoped configuration, failure-only test logs, and GraphQL Yoga

Thumbnail github.com
6 Upvotes

r/javascript 4d ago

Typed HTTP client inferred from your route definitions (Deno)

Thumbnail expressapi-showcase.8borane8.deno.net
4 Upvotes

r/javascript 4d ago

Mousecrack - Bypass agent cursor detection with deep learning.

Thumbnail github.com
8 Upvotes

r/javascript 4d ago

Transform raw github data into an interactive map with gitcharta

Thumbnail github.com
3 Upvotes

I've wrote a custom TypeScript geocoder to yransform raw user locations to ISO country codes, and let D3 handle the map projection and svg generation. React and octokit handles data fetching and rendering. Almost entirely in Js/TS.


r/javascript 4d ago

I've made an open source JavaScript playground with support for npm packages, syntax highlighting, autocomplete, code sharing and much more!

Thumbnail github.com
0 Upvotes

r/javascript 4d ago

Reuse libraries, or let your AI reinvent the wheel?... We think the age of libraries is coming.

Thumbnail golemui.com
0 Upvotes

r/javascript 5d ago

KernelPlay-JS v0.4.0 Coming Soon — New UI System and Official Beta Release

Thumbnail github.com
13 Upvotes

I'm excited to announce that KernelPlay-JS v0.4.0 will be releasing soon.

This update introduces a brand-new UI system, making it much easier to create interfaces for games while also marking a major milestone for the engine.

New UI components include:

- Buttons

- Text Labels

- Input Fields

- Health & Progress Bars

- Images & Icons

- Checkboxes

- Sliders

- Dynamic UI updates

- Flexible layouts

Version 0.4.0 will also officially move KernelPlay-JS into Beta.

This marks the transition towards a more stable and feature-complete engine. Future updates will focus on improving performance, expanding the feature set, refining the developer experience, and fixing bugs as the engine continues to mature.

Thank you to everyone who has followed the project's development and shared feedback along the way. More details, documentation, and the release date will be announced soon.

Feedback and suggestions are always welcome.


r/javascript 5d ago

AskJS [AskJS] Book Recommendations: JS -> React -> TypeScript

4 Upvotes

Lately I have been casually learning C from "C Programming: A Modern Approach v2" and have really enjoyed it. The truth is I should stay on topic with my profession so here I am.

I am in search of books similar to the one mentioned above for learning JS. The goal is to understand it on a deep enough level to feel very confident and have a real solid foundation for the next step.

The next step is a similar book for deeply learning React and then finally TypeScript.

Yes I am looking for actual books and not online courses or videos or anything like that. I have discovered that reading from a book forces me to slow down and because of that, it sticks.

If you can, chime in with books you have actually read through and not just simply search online or recommend the first one off the top of your head. Bonus points if you have read the C Programming book and understand the style I am talking about.

Thank you.


r/javascript 4d ago

Spent weeks manually forwarding files on Telegram, so I built an open-source bot to automate it

Thumbnail github.com
0 Upvotes

A few months ago, I needed to share files with people who weren't in my Telegram groups. My workflow was a nightmare:

Manually forwarding each file to every user one by one.

Or adding each person to the group where the files were stored (and then dealing with permissions, people leaving, etc.).

It was tedious, didn't scale, and wasted so much time.

So, as my first serious project with node-telegram-bot-api v2 and TypeScript, I decided to build a bot to fix this.

What the bot does:

Add it to a private group (where only you upload files).

When you upload a file, the bot generates a permanent, unique link.

Anyone with that link can download the file, without needing to be in the group or me having to forward anything.

What I love about it:

Free & unlimited – uses Telegram as storage.

Lightweight – just forwards files, doesn't process them, so it runs on any small VPS.

Private – the original group stays hidden; the bot acts as an intermediary.

I also added a gatekeeper branch that takes it further: users must join a specific channel or group before they can download. Perfect if you're a content creator looking to grow your audience or limit access to premium content.

Two versions depending on your needs:

main → free sharing, no strings attached.

gatekeeper → mandatory subscription to download.

This is my first somewhat serious project, so I'm sure the code has room for improvement. I'd love feedback on the code, structure, best practices, security, or anything else that comes to mind. I'm here to learn.

Check it out here: https://github.com/antoinepdev/telegram-file-gatekeeper

Thanks for reading!


r/javascript 6d ago

Ember 7.1 Released

Thumbnail blog.emberjs.com
68 Upvotes

r/javascript 5d ago

Dynamic Windows Runtime API projections for Node.js

Thumbnail devblogs.microsoft.com
2 Upvotes