0

I'm creating a HTML5 app and packaging with TideSDK. I'm trying to get an image to display on canvas; however try as I may, nothing is showing up. I've pinpointed the problem to the placement of the image file in the directory (I ran the same code in jsFiddle with an image from the web and it was fine), so is there a specific place where I should be placing my images so TideSDK can find it? Thanks!

$(document).ready(function() {
    var canvas = $("#game");
    var context = $("#game")[0].getContext("2d");
    context.font="18px OpenSans";
    var backImage = new Image();
    backImage.src="../images/homeBackground.jpg";
    homeScreen();

    function homeScreen() 
    {       
        context.drawImage(backImage, 0, 0);     
    }   
});

File Directory:

CGS
 |
 Resources
    |
    css
    fonts
    images
      |
           homeBackground.jpg
    js
     |
           game.js (where the above code is located)
           jquery.js
    index.html
  Dist
Andrew
  • 3,501
  • 8
  • 35
  • 54

1 Answers1

0

You are missing two things.

  1. Don't forget to set width and height attributes of the canvas
  2. Wait for the loading of the image after you set the src attribute

Here is a tested, working js code sample:

$(document).ready(function() {
    var canvas = $("#game");
    var context = canvas[0].getContext("2d");
    context.font="18px OpenSans";
    var backImage = new Image();
    backImage.onload = function() {
        homeScreen();
    };
    backImage.src="../images/homeBackground.jpg";

    function homeScreen() 
    {       
        context.drawImage(backImage, 0, 0);     
    }   
});

And don't forget to set width and height of the canvas:

<canvas id="game" width="500" height="500"></canvas>
kgd
  • 1,666
  • 2
  • 11
  • 15