【问题标题】:Html5 canvas not drawingHtml5画布不绘图
【发布时间】:2013-10-27 01:34:23
【问题描述】:

我有一个对象没有绘制它的图像的问题。我已将图像的 onload 属性设置为绘图功能..

//ctor
function Sprite(someargs,pContext)
    this.setContext(pContext); //This could be the problem?
    this.setX(px); 
    this.setY(py);
    this.setTexture(pImagePath);    


//I run this in the constructor 
Sprite.prototype.setTexture = function(pImagePath){
    this.texture = new Image();
    this.texture.onload = this.draw();  
    this.texture.src = pImagePath;
};

Sprite.prototype.draw = function(){

    this.getContext().drawImage(this.texture,this.getX(),this.getY(),100,100);
};

Sprite.prototype.setContext = function(pContext){
       this.mContext = pContext;
};

运行时没有错误,但图像未绘制到画布上。 我在上述所有方法中都设置了警报,所有这些方法都在执行。

任何人对它为什么不绘图有任何想法吗?

干杯

【问题讨论】:

  • 我认为你需要展示你如何实际实例化上下文 - 没有必要说“这可能是问题所在,但我已经删除了代码”:)
  • setContext 是在 setTexture 之前调用的吗?
  • 更新了代码,是的,我先调用 setContext
  • function Sprite(someargs,context) this.setContext(pContext); // 你的参数被称为context 但你稍后使用pContext
  • 抱歉忘记在我的编辑中更改它。代码语法全部有效

标签: javascript html canvas


【解决方案1】:
this.texture.onload = this.draw();  

您没有将onload 设置为draw 函数,而是设置为draw 函数的结果

this.texture.onload = this.draw;

也不好,因为您将在这里丢失this 的上下文。 this 内部的 draw 函数将指向 texture 而不是 Sprite

您需要将bind 函数draw 传递给this(目前是Sprite)并将其传递给onload

this.texture.onload = this.draw.bind(this);

或:

var that = this;
this.texture.onload = function() { that.draw(); }

【讨论】:

  • 啊,这太邪恶了。谢谢!
猜你喜欢
  • 2017-03-26
  • 2016-08-22
  • 2014-08-20
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多