Valentin Jacquemin

Rendering an Image via CSS linear-gradients

I’ve lately done my own exploration of what is possible with one single div element and a couple of CSS rules (see Ici c’est Fribourg and note 3156).

As I was playing with the linear-gradient function it occured to me that you can actually use it to paint single pixels. Simply use hard color stops and you can actually draw an entire line of pixels, each one in a specific color.

So. Would that be possible to draw an image using this technique?

Take an image, translate each row of pixels into a linear-gradient incantation and the browser will display the same image. Purely in CSS.

Useful? Heck no. Funny? Weirdly so. I found interesting to play with the idea and could eventually have a running example.

World Wide Web Logo
World Wide Web Logo

Which one is rendered via CSS? If you’re using LibreWolf like me it’s easy because by default a grant is required to extract data from a canvas element. Before you’d accept this you’d see that the image to the right is not correctly rendered. So yes, the image rendered only via linear-gradient rules is to the right.

Check out the source of this page to see how you can use the Canvas API to extract the color of each pixel of an image and how it’s then translated into one linear-gradient for an entire row of pixels. MDN published a nice tutorial all around pixel manipulation as well.