Javascript Builder for DrawImage Canvas Function

2

I need to draw several images on various canvas, so I would like to do a generic function that would allow me to pass the arguments to draw the positioned images.

I thought of the following generic function:

var drawIt = new function(CanvasCtx,drawObj,x,y) {
   this.CanvasCtx = CanvasCtx;
   this.drawObj = drawObj;
   this.x = x;
   this.y = y;
      this.drawObj.onload = function(){
         this.CanvasCtx.drawImage(this.drawObj,this.x,this.y)
      }
}

Then when I set the Canvas and the image:

var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");

var Image1 = new Image();
Image1.src = "https://www.google.com.br/images/srpr/logo11w.png";

I could define a function to start on body load:

function drawScreen(){
   drawIt(ctx,Image1,100,100);
}

But I get the error that the onload property can not be assigned to an unidentified object.

Can anyone help me build this generic function?

    
asked by anonymous 03.03.2014 / 23:26

1 answer

2

The problem is that you are running a constructor at the same time that you define it (because of new , as pointed out by Gustavo Rodrigues). So all the parameters you are passing are undefined .

The quickest move is to move the first block of code into drawScreen , but if I understood your code well, I would rewrite everything in a simpler way, without using a constructor or this . This even fixes a problem you'd find straight away because the value of this within onload would not be what you expect ... My suggestion is to use this:

var drawIt = function(canvasCtx, drawObj, x, y) {
   drawObj.onload = function(){
       canvasCtx.drawImage(drawObj, x, y);
   }
}

Usage is how you predicted it:

var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var Image1 = new Image();
Image1.src = "https://www.google.com.br/images/srpr/logo11w.png";

function drawScreen(){
   drawIt(ctx,Image1,100,100);
}

drawScreen();

Example in jsfiddle

    
04.03.2014 / 00:18