0

I was trying to draw an image (png-file) to a to act as a background-image and I do not know why the js i have thus far is not working.

Here's what I have:

var canvas = document.getElementById('hplogo-z');
var cnvs = canvas.getContext('2d');
background = new Image();
background.onload = function(){
  cnvs.drawImage(background, x, y);
}
background.src = 'bg.png';

Any ideas on what I am doing wrong?

Phrogz
  • 271,922
  • 98
  • 616
  • 693
theirf
  • 5
  • 5
  • 4
    Did you define `x` any `y` anywhere? – John Stimac May 14 '12 at 20:56
  • I assume your browser is showing you an error, likely that "x is not defined". Open your error console and look. – Phrogz May 14 '12 at 21:11
  • @Phrogz: i forgot to define x & y, but i tried replacing it with 0, 0 and the image still doesn't show. – theirf May 14 '12 at 21:18
  • @Jcubed : I forgot to define them, but when i replaced x and y with numbers, the image still doesn't appear. – theirf May 14 '12 at 21:21
  • @theirf Are there errors in your error console? Can you make a simple pared-down test case at http://jsfiddle.net reproducing your problem? What OS/browser/version are you using? Are you certain that the relative path to that image is correct? Are you sure that the image can actually be loaded? – Phrogz May 14 '12 at 21:26
  • Finally: are you sure that you need to draw the image to the canvas, instead of just [setting a CSS background](http://stackoverflow.com/questions/5241365/how-to-set-the-background-image-of-a-html-5-canvas-to-png-image)? – Phrogz May 14 '12 at 21:27
  • It's a long shot, but are you setting `background` to another value after this code snippet? – apsillers May 14 '12 at 22:12
  • @apsillers : no, i don't believe so. – theirf May 15 '12 at 01:37
  • @Phrogz : Well, I wanted to try drawing an image first before I tried the CSS solution. [Here is the JS fiddle] (http://jsfiddle.net/jaxBc/) Same issue, just a blank canvas with no image is drawn. – theirf May 15 '12 at 01:38
  • 1
    @theirf There's a syntax error with your fiddle. I've [fixed it](http://jsfiddle.net/jaxBc/1/) and it works fine(you had an extra http://). – Daedalus May 15 '12 at 02:03

1 Answers1

1

I was unable to reproduce your problem, so the only things I can guess are that your path is wrong or there is something wrong with your image.

I would recommend you attempt to replace your current path with something from placehold.it, or use a different image in a different location in order to see if your image/path is indeed the problem.

Daedalus
  • 7,518
  • 3
  • 29
  • 56