Images and Text - Exercise

Contact Us or call 1-877-932-8228
Images and Text - Exercise

Images and Text

Duration: 30 to 40 minutes.

In this exercise, you will start with two images found in the html5-canvas/Exercises/Images folder:

  1. south-america.gif - a map of South America.
  2. flags.png - a picture containing small graphics of country flags.

You will create the following drawing: Drawing of South America

Notice the text over the graphics.

  1. Open html5-canvas/Exercises/south-america in your editor.
  2. Add the JavaScript code necessary to:
    1. Create the image objects and set their source values.
    2. Draw the backdrop (the map).
    3. Place the flags using the sprite method shown earlier. Each flag is 18 pixels wide and 13 pixels high. The source and destination positions are shown in the table below.
    4. Add the country names.
Country Source X Source Y Destination X Destination Y
Chile 283 88 100 250
Argentina 255 4 130 300
Brazil 171 60 200 170
Paraguay 59 452 170 250
Uruguay 59 564 185 310
Bolivia 59 200 135 210
Peru 31 424 75 170

Solution:

html5-canvas/Solutions/south-america.html
<!DOCTYPE HTML>
---- C O D E   O M I T T E D ----
	if (canvas.getContext) {
		var context = canvas.getContext("2d");
		
		//variable to hold background image:
		var backdrop = new Image();  

		//variable to hold flags image:
		var flags = new Image();  

		//set source of backdrop:
		backdrop.src = 'Images/south-america.gif';

		//set source of flags:
		flags.src = 'Images/flags.png';

		backdrop.onload = function() {  
			context.drawImage(backdrop,0,0);  
		} 

		flags.onload = function() {
			//draw images using "sprite" method, rendering individual
			//flags from the image containing multiple flags
			context.drawImage(flags, 283, 88, 18, 13, 100, 250, 18, 13);
			context.fillText("Chile",100, 250);
			context.drawImage(flags, 255, 4, 18, 13, 130, 300, 18, 13);
			context.fillText("Argentina",130, 300);
			context.drawImage(flags, 171, 60, 18, 13, 200, 170, 18, 13);
			context.fillText("Brazil",200, 170);
			context.drawImage(flags, 59, 452, 18, 13, 170, 250, 18, 13);
			context.fillText("Paraguay",170, 250);
			context.drawImage(flags, 59, 564, 18, 13, 185, 310, 18, 13);
			context.fillText("Uruguay",185, 310);
			context.drawImage(flags, 59, 200, 18, 13, 135, 210, 18, 13);
			context.fillText("Bolivia",135, 210);
			context.drawImage(flags, 31, 424, 18, 13, 75, 170, 18, 13);
			context.fillText("Peru",75, 170);
		}
	}
---- C O D E   O M I T T E D ----

Next