Let the Browser Do the Math Or: How I Learned to Stop Worrying and Love the DOM

As I’ve been working on My Mind is Racing, I’ve been trying to make the pages look nicer when they are shared. That means adding an og:image meta property:

#Doing it the hard way first

The Open Graph (og) metadata gives you more control over how a page preview renders on Reddit, LinkedIn, [insert name of social media walled garden]. Of course adding the metadata also means producing an appropriate image. This is my top level og:image:

That’s nice, but it might be a bit weird to show this card for a small town with one or two events. Since I have lots of data to work with, I thought it would be fun to create different cards. I would customize the card display based on the country, region and city of the page being shared. This meant getting a nice design and then rendering all of the cards with a Golang library. This was fine, but it got a bit fiddly when I had to do things like use a specific font or calculate how large the font needed to be and how the text should be positioned when a place name, for example, was longer than I had been expecting.

You can totally solve this problem with math, but I don’t want to. HTML is really good at reflowing text, repositioning one thing when another thing moves, adding a bit of padding here and there. You see where I’m going with this? Instead of using more complicated math, I opted for a more complicated workflow and on a very high level it looks like this:

#The workflow

flowchart TD
Data["Your params
city, region, events"] -->|"as a query string"| Get["GET the template page
/template?city=Toronto#amp;region=Ontario#amp;events=28"] Get --> Render["Headless browser loads the HTML;
JS reads the params, CSS lays out the card"] Render --> Shot["Screenshot the #card element"] Shot --> PNG["PNG image"]

Easy, right? That workflow essentially produces this image for Toronto:

#Render it with a headless browser

It turns out that once…

添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论