Processing.js

Adding existing images to a Sketch's ImageCache

Example 1. Loading an image from the DOM

Sometimes a developer wants to share images between a Processing sketch and the web page in which it lives. This might happen in a complex page where images are loaded at different times, and a sketch runs after the images are loaded by the web page itself. In such cases, it is helpful to be able to pass a preloaded image into the sketch's image cache, so it won't get loaded a second time before the sketch starts. The following example demonstrates this, by loading an image into the DOM by means of the img element, and then creating a Processing Sketch object in JavaScript that uses this image, without doing any other preloading.

Image Element

Processing Sketch in Canvas



Example 2. Loading an image using only JavaScript

This example is similar to Example 1, but bypasses the DOM altogether and creates an image using JavaScript. This technique is useful when you want to background load images, but not display them yet.