Reputation: 322
I am trying to create an object that will create an image and draw it on canvas. The reason I am not just the regular image object is that I want to know where the objects are place on the canvas for mouse actions.
Here is my constructor function:
function DisplayImg(src, x, y, w, h) {
this.src = src;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
I create a draw function to draw it to the canvas:
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);
}
}
I then make an API call to instagram and grab some photo urls and put them in an array. Here I am trying to loop through that array and create an object for each one, and draw it to the canvas. I can console.log the data and see the image src's so I know the data is there. This is the function I call once I get the data back:
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);
}
}
My logs return the correct data, but none of the images are drawn to the canvas. Any help is greatly appreciated.
Upvotes: 0
Views: 3241
Reputation: 318
First thing you should do is fix your prototype function:
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;
}
You're passing garbage values to the context.drawImage function because "this" no longer applies to your DisplayImage instance inside of that onload function, this should remedy that.
Secondly, make sure you are actually passing a correct context through, not much I can help you there with. I made a fiddle that examples your code, but I had to change your "draw" function to make it sane: http://jsfiddle.net/yuaHF/2/
Upvotes: 1