Skip to content Skip to sidebar Skip to footer

Using Images As Buttons On Html Canvas

So I've managed to get javascript code to track the cursor over images displayed on an html canvas thanks to markE, but now I'm trying to treat each one of the images as a button a

Solution 1:

Your fix is to preload all your images before using them.

Images do not load immediately. When you set the img.src the browser begins loading the image but also continues onto the next line of code even before the image is fully loaded.

The problem is here:

// the browser BEGINS to load the image, but simultaneously
// continues executing the code that follows.
img.src = imgSrc;

// img has not yet loaded when drawImage is executed 
ctx.drawImage(img, 564, 265 );

There are dozens of image pre-loaders available. Here's just one:

// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// put the paths to your images in imageURLs[]
var imageURLs=[];  
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face1.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face2.png");

// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
startLoadingAllImages(imagesAreNowLoaded);

// Create a new Image() for each item in imageURLs[]
// When all images are loaded, run the callback (==imagesAreNowLoaded)
function startLoadingAllImages(callback){

  // iterate through the imageURLs array and create new images for each
  for (var i=0; i<imageURLs.length; i++) {
    // create a new image an push it into the imgs[] array
    var img = new Image();
    // Important! By pushing (saving) this img into imgs[],
    //     we make sure the img variable is free to
    //     take on the next value in the loop.
    imgs.push(img);
    // when this image loads, call this img.onload
    img.onload = function(){ 
      // this img loaded, increment the image counter
      imagesOK++; 
      // if we've loaded all images, call the callback
      if (imagesOK>=imageURLs.length ) {
        callback();
      }
    };
    // notify if there's an error
    img.onerror=function(){alert("image load failed");} 
    // set img properties
    img.src = imageURLs[i];
  }      
}

// All the images are now loaded
// Do drawImage & fillText
function imagesAreNowLoaded(){

  // the imgs[] array now holds fully loaded images
  // the imgs[] are in the same order as imageURLs[]

}

Post a Comment for "Using Images As Buttons On Html Canvas"