Hacker News new | ask | show | jobs
by dietrichepp 2100 days ago
There’s a simple trick you can use if you want to generate the distance field for text or simple shapes in the browser. The way you do it is by repeatedly drawing the text with strokeText, varying the stroke width and the stroke color.

For example, you fill the background with 100% white, and then draw a 10px stroke at 90% gray, 9px at 80%, 8px at 70%, etc. This is, most importantly, an extremely fast way to generate a distance field for text from JavaScript in the browser.

I mention this because the mystery of the getDistance() function is often one of the tricky parts of demos like these.

3 comments

Author here. That's a neat trick!

> I mention this because the mystery of the getDistance() function is often one of the tricky parts of demos like these.

I agree! In the demos I use a library I wrote to generate 2D distance fields: https://github.com/ryankaplan/gpu-distance-field

It's also pretty fast :)

Computing distance fields with a jump flooding approach in O(n log n) is neat, but there is a O(n) algorithm, which might be faster https://prideout.net/blog/distance_fields/
Neat! In my experience jump flooding on the GPU is faster than any CPU side approach for images bigger than a few hundred pixels. It's O(n ^ 2 log n) which sounds really expensive, but it requires just O(log n) draw calls.

The link you provided also describes a GPU amenable approach, but it says that jump flooding on the GPU is faster.

> For a more efficient GPU-amenable method, see also jump flooding by Rong and Tan. Their method generates a closest point coordinate field from which a distance field can be derived.

I don't get it how would this help you to write a function to get distance to a shape from any point on a canvas.

Edit: oh wait, you measure the pixel color :) nice

That is really awesome, thank you.