In p5, an image must be loaded into memory before it is displayed on the page.
In order to be sure that the image data is loaded before the program tries to use it, a new function is used, called
preload actually happens before the
start function, and it makes the program wait until it is done loading data before
start is invoked.
The way that media is loaded in browsers is a big part of why we use Brackets and the Live Server Preview feature for this class.
If you try opening a sketch with an image loaded into it by just opening the file in a browser, you will get a Cross Origin error and the sketch will not run. When you open a file directly in the browser, you know because the URL will look something like this:
And the sketch will be stuck loading. If you open the console, you may see an error like this:
Access to Image at 'file:///Users/oroberts/Desktop/mmp210/examples/image/imgs/cat.png' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.
By default, Chrome and some browsers will block files being loaded into a webpage from different origins. This is a security measure to prevent attacks from front end scripts.
Using Sublime Text's Package Control, we can start a live server for testing.
In Sublime, go to
Then open the
A text input interface will appear. Type
Install and then hit enter when
When a new input appears, type
SublimeServer and hit Enter. Sublime will take a moment to install the package.
Once it's done you will be able to run a server by going to
That server address is a local address on your computer.
This local server allows us to use external media like images, sounds and video.
The first argument of the
image() function is the variable referencing the image data. The second and third are the x and y coordinate where the image will be drawn.
Those values can be used to make the image change position interactively.
We can add two more arguments for width and height.
tint() function can be used to change the color and add transparency.
image(img, 0, 0, 100, 100);
image(img, 0, 0, mouseX, mouseY);
Get pixel color
We can also get the color of the image at specific pixels using the