Javascript Constructor for Canvas Drawimage function

Asked

Viewed 491 times

2

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

I thought about 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)
      }
}

So 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/images/srpr/logo11w.png";

I could set a function to start on body load:

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

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

Can someone help me build this generic function?

  • There are some problems in the code: what is the value assigned here? this.y = ; That one new is not necessary: new function(...)

  • Interestingly browsers run the code from new function but ignore the arguments. The nodejs creates an object that cannot be called: typeof drawIt === 'object'

  • I found out why the new function is valid: https://gist.github.com/qgustavor/9336704

  • @Gustavorodrigues new function(){} is the same thing as new referenciaDeFuncaoQualquer(). The point is that it runs immediately. Basically, this code defines the constructor and invokes it right away.

  • That’s kind of what I put in gist.

1 answer

2


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

The fastest move is to move the first block of code into drawScreen, but if I understood your code correctly, I would rewrite everything in a simpler way, without using a this. This even solves a problem that you would find just ahead of time, because the value of this within the 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);
   }
}

Use is as you predicted:

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

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

drawScreen();

Example in jsfiddle

  • It worked! You’re right, your solution is simpler and straightforward.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.