Preloading images with Promises
Created for answer to http://stackoverflow.com/questions/33227771/javascript-canvas-for-loops-and-drawimage-not-working-together
by UselessCode
HTML
<canvas id ="canvas" width = "500" height = "500"></canvas>
<button id="redraw">Redraw</button>
<div id="image-names"></div>
CSS
#canvas {
border: 1px #f00 solid;
}
JavaScript
var images,
nameList = document.getElementById('image-names'), // just a div to display the stuff you were writing out to document. write.
// this function returns a Promise which will resolve once all of the
// images are done loading
preloadImages = function () {
var imagePromises,
sources = [
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_00.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_01.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_02.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_03.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_04.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_05.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_06.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_07.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_08.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_09.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_10.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_11.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_12.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_13.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_14.png"
];
// if we have already loaded and cached the images,
// return them right away wrapped in a resolved Promise
if (images) {
nameList.innerHTML += 'Using cached images.<br>';
return Promise.resolve(images);
}
// otherwise we use .map to iterate over the items in sources and
// create a new array of promises and store them in imagePromises
imagePromises = sources.map(function (src) {
// each of the promises that are created by this function
// are stored in imagePromises and will resolve when the image
// it represents...