Lurker News
Paste the following into the console of any HN page - for annotated avatars on all HN comments. (self contained code)

  for(u of document.querySelectorAll('.hnuser'))for(u.prepend(c=document.createElement('canvas')),x=c.getContext('2d'),c.width=18,c.height=14,s=u.innerText,r=1,i=28+s.length;i--;i<28?r>>>29>X*X/3+Y/2&&x.fillRect(6+2*X,2*Y,2,2)&x.fillRect(6-2*X,2*Y,2,2):r+=s.charCodeAt(i-28,x.fillStyle='#'+(r>>8&0xFFFFFF).toString(16)))r^=r<<13,r^=r>>>17,r^=r<<5,X=i&3,Y=i>>2

Comments (493) 108 threads

onion2k7 replies#
This is fun.

One suggestion.. rather than creating a canvas for each user using a querySelectorAll and a loop, I'd use an IntersectionObserver and only create the canvases as they scroll into view. That way the user's device won't need to create hundreds of elements when the code runs.

    let observer = new IntersectionObserver(
    (entries) => {
        entries.forEach((entry, i) => {
        if (entry.isIntersecting) {
            const p = 2;
            const c = document.createElement('canvas');
            const x = c.getContext('2d');
            c.width = 18;
            c.height = 14;
            const s = entry.target.innerText;
            const r = 1;

            if (s) {
            for (
                let s = entry.target.innerText, r = 1, i = 28 + s.length;
                i--;

            ) {
                // xorshift32
                (r ^= r << 13), (r ^= r >>> 17), (r ^= r << 5);
                const X = i & 3,
                Y = i >> 2;
                if (i >= 28) {
                // seed state
                r += s.charCodeAt(i - 28);
                x.fillStyle =
                    '#' + ((r >> 8) & 0xffffff).toString(16).padStart(0, 6);
                } else {
                // draw pixel
                if (r >>> 29 > (X * X) / 3 + Y / 2)
                    x.fillRect(p * 3 + p * X, p * Y, p, p),
                    x.fillRect(p * 3 - p * X, p * Y, p, p);
                }
            }
            }

            entry.target.prepend(c);
        } else {
            if (entry.target.firstChild.tagName === 'CANVAS')
            entry.target.firstChild.remove();
        }
        });
    },
    { rootMargin: '0px 0px 0px 0px' }
    );

    document.querySelectorAll('.hnuser').forEach((user) => {
    observer.observe(user);
    });
Farow1 reply#
Does the canvas need to be created and removed as it comes in and out of view? Using requestAnimationFrame() might also further improve responsiveness.
onion2k1 reply#
Does the canvas need to be created and removed as it comes in and out of view?

Not really. You could just create them and not bother removing them. You'd need to check if the user already had an avatar if you did that though, or you'd end up with lots of repeated avatars when you scroll up and down the page.

dncornholio#
Or just generate them on page load and call it a day. No bugs, no complexity, no edge cases.

Could it be faster? Sure, but should it be faster? Not really, IMO, the avatars load very quick, even on a big page.

myfonj2 replies#
Speaking performance/optimisations, interesting choice to destroy canvas when it leaves viewport and recreate it upon each re-entry.

Personally I'd leave it created and stop observing the element instead, à la

    /* … */ if (entry.isIntersecting) { observer.unobserve(entry.target); /* … */ }
Do you think (or know) that swapping observed node for canvas (potentially producing many canvases) is more expensive than keeping all observers and having smallest possible amount of canvases? (Maybe I'm biased towards saving CPU but saving RAM is better after all?)
onion2k#
That's a really good idea. Definitely something to measure, but I suspect you're right.
eyelidlessness#
If it turns out there’s some upper bound where caching canvases in memory becomes a problem (eg large threads become not paginated), it’s pretty trivial to build a cache around [Weak]Map and get the ~best of both worlds.
squiffy#
This is great, thanks. A small fix I made to stop console warnings was to change:

  x.fillStyle = '#' + ((r >> 8) & 0xffffff).toString(16).padStart(0, 6);
to:

  x.fillStyle = '#' + ((r >> 8) & 0xffffff).toString(16).padStart(6, '0');
as the pad target length is the first parameter of padStart.
tomxor1 reply#
Thanks, Interesting idea. I'm a little sceptical of the performance improvement, but I suppose that depends what we mean by performance.

Your strategy essentially trades a one time computation and DOM mutation with a continuous but lighter one with some added overhead. In this case I suspect the total power performance is worse over time; _however_ latency and UX should be _better_, since it removes the relationship between total comments on the page and the time to render avatars, which is currently about 100ms for this page on my machine.
I'm definitely biased towards preferring a one time change and making it as efficient as possible, but when the input has a high enough ceiling I can see how your strategy would make more sense - I'm not quite sure where I stand on HN threads - but thankfully this is just a user script so we can make our own choices :)

styfle1 reply#
I wonder how `` would compare to `` instead
tomxor#
Yes! it did cross my mind, I was just more familiar with canvas API so I cracked on with it... but I suppose encoding a simple format like bitmap would be trivial, almost like being able to access the canvas pixel buffer but with a lower overhead.

This thread is a good perf test, I might give it a quick go.
Also as others mentions the pixelation style thing is now finally fully cross browser supported, which should make it easier to achieve nearest neighbour upscaling for url encoding.
[edit]
I underestimated how involved image format headers are!

joeraut#
A nice improvement! An unfortunate side-effect of it is that it introduces some jitter during macOS's smooth scrolling in Firefox at time of first render, though.
phplovesong#
Awesome! I did not know about IntersectionObserver. Will def add this to my toolbox! Thanks!
eurasiantiger#
A better optimization would be adding appropriately sized SVG tags to comments before first paint (to prevent re-flowing the layout) and lazily generate avatars to a SVG sprite sheet. No canvas required.
INTPenis8 replies#
Hah! I got a really cool little icon that looks almost like the cassette tape pirate logo of Piratbyrån back in the day. I have old t-shirts with that logo.

MAKE. THIS. PERMANENT!
On the functional side, this really helps you see who is who in a long threaded discussion. Your eye is much quicker at following the little color icons than their names.

hwers1 reply#
I'm gonna go ahead and vote no on this.
INTPenis2 replies#
But your avatar looks like a Ninja Turtle with shades on. You should be enjoying this. :)
k4rli4 replies#
Likely still traumatized by existence of new reddit UI. Old appears to be better.

Continue this thread — 4 replies

neogodless#
Wow, I thought it was a green camper van!
Cthulhu_2 replies#
It should be fairly straightforward to turn this into a browser addon, give users a choice and offload the people behind HN.
edmcnulty1012 replies#
What is a user script?

Continue this thread — 2 replies

libele1 reply#

  // ==UserScript==
  // @name        HN Avatars in 357 bytes
  // @description Annotated avatars on all HN comments.
  // @author      tomxor (https://news.ycombinator.com/user?id=tomxor)
  // @namespace   https://news.ycombinator.com/item?id=30668137
  // @include     https://news.ycombinator.com/item*
  // @include     https://news.ycombinator.com/user*
  // @grant       none
  // @version     1.0.0
  // ==/UserScript==

  [js goes here]

Continue this thread — 1 reply

rb666#
Doesn't work on FF does it?
bertman4 replies#
>MAKE. THIS. PERMANENT!

I second this. (Also I wanted to see what my avatar looks like, sry)

david927#
How dare you! Edit: ooooh, mine's a beetle!
gaetgu1 reply#
Truly unacceptable. (I look like an alien head!)
ChrisClark9 replies#
But Space Invaders is a classic!

Continue this thread — 9 replies

romellem1 reply#
This is fun, and can easily be added as a userscript. I might look to do that a little later.
notsound3 replies#
// ==UserScript== // @name HN icons // @namespace https://news.ycombinator.com/* // @version 0.1 // @description try to take over the world! // @author some people on HN // @match https://news.ycombinator.com/* // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== // @grant none // ==/UserScript==

(function() { // Initial concept is from: https://news.ycombinator.com/item?id=30668137 (tomxor) // The script we are using is from: https://news.ycombinator.com/item?id=30670079 (onion2k) 'use strict'; let observer = new IntersectionObserver( (entries) => { entries.forEach((entry, i) => { if (entry.isIntersecting) { const p = 2; const c = document.createElement('canvas'); const x = c.getContext('2d'); c.width = 18; c.height = 14; const s = entry.target.innerText; const r = 1;

            if (s) {
            for (
                let s = entry.target.innerText, r = 1, i = 28 + s.length;
                i--;

            ) {
                // xorshift32
                (r ^= r << 13), (r ^= r >>> 17), (r ^= r << 5);
                const X = i & 3,
                Y = i >> 2;
                if (i >= 28) {
                // seed state
                r += s.charCodeAt(i - 28);
                x.fillStyle =
                    '#' + ((r >> 8) & 0xffffff).toString(16).padStart(0, 6);
                } else {
                // draw pixel
                if (r >>> 29 > (X * X) / 3 + Y / 2)
                    x.fillRect(p * 3 + p * X, p * Y, p, p),
                    x.fillRect(p * 3 - p * X, p * Y, p, p);
                }
            }
            }

            entry.target.prepend(c);
        } else {
            if (entry.target.firstChild.tagName === 'CANVAS')
            entry.target.firstChild.remove();
        }
        });
    },
    { rootMargin: '0px 0px 0px 0px' }
    );

    document.querySelectorAll('.hnuser').forEach((user) => {
    observer.observe(user);
    });
})();

Continue this thread — 3 replies

simcop2387#
This should be pretty easy to make into a userscript if browsers still support that. I haven't checked on that in half a decade or so

also i wanted to see mine too

WithinReason#
> Hah! I got a really cool little icon that looks almost like the cassette tape pirate logo of Piratbyrån back in the day.

I think it's a skeleton holding his arms up!
edit: Looks like I'm some green bug-monster

MisterSandman4 replies#
I do feel like HN needs avatars of some kind... just don't know if they should be customizable or fixed (like this one).
MisterSandman#
Looks like I got blue transformer/reinhardt
INTPenis#
Definitely not customizable, that's chaos.

Unique, fixed little color doodads make it easier to see who's who in a thread.

Duralias#
With how pretty much every platform has "avatars", that the user can customize, I think it would be fun just getting one assigned to you.

Edit: Huh, I got an alien house. Reminds me of some game.

sexangel1 reply#
I'm for the fixed avatars. We are all born with certain unchangeable aspects.

Continue this thread — 1 reply

Continue this thread — 3 more replies

chrismorgan3 replies#
For better rendering on high-DPI screens and (more subjectively) screens of people that have zoomed in because HN’s text sizes are unreasonably small, add c.style.imageRendering='pixelated'.

I was going to say that the insertion of these 24 bytes allows you to save ten bytes elsewhere by halving the size of the image (making features one pixel in size, rather than two), but then you’d also have to set the doubled image dimensions, and that’d cost more than ten bytes.
(Me, I use HN at 120% on top of a native scaling factor of 150%, which is currently implemented as downsampling of 200% rendering because Firefox hasn’t got fractional scaling right yet under Wayland, and widget.wayland.fractional_buffer_scale has some fairly debilitating side-effects on popup windows including non-rendering and crashes, which is a pity because it improves rendering so very much.)

Continue this thread — 3 replies

alainchabat233 replies#
Reply here if you just want to see how your username looks like, so we avoid noise and keep that Show HN on the top. comments are really interesting

Continue this thread — 233 replies

Load more comments