Using the background function of Processing.js with images

“Background image must be the same dimensions as the canvas.”

In case you are looking for a workaround for Processing.js background function that forces you to scale your background image, try this trick to make your browser do the scaling for you.

Set the CSS background for the canvas element to your image, and use “cover” or “contain” to stretch your background to fit the canvas:

<canvas style="background: url(<!-- your background image path -->); 
  background-size: cover"></canvas>

In your JS, you can set Processing’s background opacity to zero alpha (transparent), or simply use clearRect without the help from Processing:

background(0, 0);
// OR
document.getElementById('canvas').getContext('2d')
  .clearRect(/* x */, /* y */, /* w */, /* h */);

Of course you can dynamically set the CSS of the canvas in your script whenever you feel like changing your background image.

0 thoughts on “Using the background function of Processing.js with images”

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: