Scott
Scott

Reputation: 6746

HTML Canvas fails to drawImage

Given the following two objects:

function newDoodle() {
  var Doodle = {
    /* Variables for creating the canvases */
    cnvWdth: 800, 
    cnvHght: 250,
    bgCanvas: false,
    fgCanvas: false,
    bgContext: false,
    fgContext: false,
    bodyElement: false,

    /* Variables for future objects */
    background: false,

    init: function(bodyElement) {
      /* Set up the two canvas elements */
      this.bodyElement = bodyElement;
      this.bgCanvas = this.createCanvas('background');
      this.fgCanvas = this.createCanvas('foreground');
      this.bgContext = this.getContext(this.bgCanvas);
      this.fgContext = this.getContext(this.fgCanvas);

      /* Set up the background canvas */
      this.bgImage = newBackground();
      this.bgImage.init(this.bgContext);
    },

    createCanvas: function(id) {
      var canvas = $('<canvas />').appendTo(this.bodyElement);
      canvas.attr('width', this.cnvWdth);
      canvas.attr('height', this.cnvHght);

      return canvas[0];
    },

    getContext: function(canvas) {
      var context = canvas.getContext('2d');
      return context;
    }
  }
  return Doodle;
}

function newBackground() {
  var Background = {
    /* Background Image source variables */
    srcXPos: 0,
    srcYPos: 0,
    srcWdth: 800,
    srcHght: 250,

    bgImage: new Image(),
    bgImageSrc: 'doodle_background.png',
    context: false,

    init: function(ctx) {
      this.context = ctx;
      this.bgImage.addEventListener('load', this.drawBackground(), false);
      this.bgImage.src = this.bgImageSrc;
    },

    drawBackground: function() {
      this.context.drawImage(this.bgImage, 0, 0);
    }
  }
  return Background;
}

I store newDoodle()'s returned object into a variable and call its init function. Ultimately it will call newBackground()'s object's drawBackground() function. I've verified that both the image and contexts are valid, and even with "use strict", nothing is reported in the console, yet nothing is getting drawn to the canvas. What am I missing?

Upvotes: 1

Views: 309

Answers (1)

balpha
balpha

Reputation: 50958

This line is the culprit:

this.bgImage.addEventListener('load', this.drawBackground(), false);

See how you're calling this.drawBackground right here, and not passing it as an event handler?

What you probably want is this:

var that = this;
this.bgImage.addEventListener('load',
    function () { that.drawBackground(); }, false);

Note that you cannot shorten to

this.bgImage.addEventListener('load',
    this.drawBackground, false); // will not work!

since drawBackground needs the context – the this context, not the canvas context. Well, that too. Anyway, I digress :)

Upvotes: 1

Related Questions