Neill's Blog

  • HowTos
  • Personal
  • Recipes
  • Technical
  • Technology

Using a canvas for a dynamic(ish) background image

Published: Wed 09 March 2022
By Neill Cox

In HowTos.

tags: HowTo css

Using a canvas to provide a dynamic background

For tedious reasons the image I had chosen for this blog's background wasn't suitable.

A bit of googling found the suggestion of using a dynamically generated image as a background via a canvas.

The one I settled on is from https://codepen.io/tmrDevelops/pen/wMJNjr - that makes a nice abstract grey patterned background.

Figuring out exactly how to use that for my use case sent me down a few rabbit holes.

I basically ended up using the script from above with a few minor modifications.

At the start of the script

var c = document.getElementById('canv') 

Becomes

var c = document.createElement('canvas');

And at the end add:

document.getElementById('index').style.backgroundImage = "url(" + c.toDataURL("image/png")+ ")";

Credit for this solution to https://stackoverflow.com/a/9369248 (modified slightly because that solution assumes jquery)

This method means that the background no longer updates on events, it's generated once when the page loads. I may try to fix this later, but I don't really care all that much.

Proudly powered by Pelican, which takes great advantage of Python.

The theme is based on Smashing Theme, thanks!

The background comes from code developed by tmrDevelops