HTML Canvas无法绘制图像

时间:2012-03-27 02:43:04

标签: javascript canvas

给出以下两个对象:

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;
}

我将newDoodle()的返回对象存储到变量中并调用其init函数。最终它将调用newBackground()的对象的drawBackground()函数。我已经验证了图像和上下文都是有效的,即使使用"use strict",控制台中也没有报告任何内容,但是没有任何内容被绘制到画布上。我错过了什么?

1 个答案:

答案 0 :(得分:1)

这条线是罪魁祸首:

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

在这里查看您调用 this.drawBackground的方式,而不是作为事件处理程序传递?

你可能想要的是:

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

请注意,无法缩短为

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

因为drawBackground需要上下文 - this上下文,而不是画布上下文。嗯,那也是。无论如何,我离题了:))