2012-08-16 33 views
0

我正在嘗試創建一個將創建圖像並在畫布上繪製的對象。我不只是常規圖像對象的原因是我想知道對象放置在畫布上的鼠標操作的位置。在畫布中創建自定義圖像對象

這裏是我的構造函數:

function DisplayImg(src, x, y, w, h) { 
      this.src = src; 
      this.x = x; 
      this.y = y; 
      this.w = w; 
      this.h = h; 
     } 

我創建了一個平局功能,把它畫到畫布:

DisplayImg.prototype.draw = function(context) { 
      img = new Image(); 
      img.src = this.src; 
      img.onload = function() { 
      context.drawImage(img,this.x,this.y,this.w,this.h); 
      } 
     } 

我再進行API調用的Instagram和抓住一些照片的URL和把它們放在一個數組中。在這裏,我試圖循環訪問該數組,併爲每個數組創建一個對象,然後將其繪製到畫布上。我可以console.log數據並看到圖像src的,所以我知道數據在那裏。這就是我所說的功能,一旦我得到的數據傳回:

function draw() { 
      for (var i = 0; i < srcArr.length; i++) { 
      var src = srcArr[i]; 
      x = Math.floor(Math.random()*8); 
      y = Math.floor(Math.random()*8); 
      var theImage = new DisplayImg(src,x,y,75,75); 
      theImage.draw(context); 
      } 
     } 

我的日誌返回正確的數據,但沒有任何圖像繪製在畫布上。任何幫助是極大的讚賞。

回答

1

你應該做的第一件事是確定你的函數原型:

DisplayImg.prototype.draw = function(context) { 
    var display = this, 
     img = new Image(); 
    img.onload = function() { 
     context.drawImage(img,display.x,display.y,display.w,display.h); 
    } 
    img.src = this.src; 
} 

你傳遞的垃圾值的context.drawImage功能,因爲「這個」不再適用於您的DisplayImage實例的onload函數內,這應該補救。其次,確保你確實傳遞了一個正確的上下文,並沒有太多可以幫助你。我做了一個小例子你的代碼,但我不得不改變你的「繪製」功能,使其理智:http://jsfiddle.net/yuaHF/2/

+0

感謝您的洞察力,我現在可以得到一些圖像顯示。 – dotfury 2012-08-16 16:25:13

+0

很高興我能幫到你。 – 2012-08-16 21:24:38