Lesson 12

Random Image

Selecting a random image

Now we are generating two random numbers, we can use these to change the images displayed in our canvas elements.

1. Create image variables

Create two new variables to store the random images. We could use any names here, but 'img1' and 'img2' are short and clear.

2. Create URL variables

Next we create two new variables to store the location of our images. We combine the 'img' variables with the required CSS syntax 'url("");' to produce the final URL needed to locate the image. As the images are changing randomly we need to use dynamic information

Why have we used + in the code?

A plus in JavaScript combines two things together. We’re using it here to mix a variable [e.g. img1] with the opening CSS code [ url(" ] and the closing CSS code [ "); ] , but if these were numbers it would add them together.

Go to the next lesson

index.html

script-1.js

the web page

New Window
Next Lesson