Javascript: image.onload function inside "class"

Started by
3 comments, last by Martin Mako Truba? 10 years, 3 months ago

Greetings,

I am messing with JavaScript a little. I have a "class", that represents image. Inside that class, I try to assign a function to image.onload event.


			var Card = function(url,c){
				this.url = url;
				this.ctx = c;
				this.img = new Image();
				this.posxCurr = 0;
				this.posyCurr = 0;
				this.widthCurr = 100;
				this.heightCurr = 100;
				this.img.onload = this.imageLoaded.bind(this);
				this.img.src = this.url;
			};
			

			Card.prototype = {
				imageLoaded : function(){
					//my goal is to initialize this.widthCurr and this.heightCurr
					this.widthCurr = this.img.width;
					this.heightCurr = this.img.height;
					alert('mako');
					console.log(this.img.width);
				},
				
			};

Basically I am trying to set widthCurr and heightCurr to actual size of the image after it is loaded. The function imageLoaded() seems not to be executed at all - there is no alert and when I draw the image, it is 100x100. What am I doing wrong?

Thanks for answers.

Mako

Advertisement

Edit:

Be sure to use a polyfill if you want to be compatible to IE < 9

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Jan F. Scheurer - CEO @ Xe-Development

Sign Up for Xe-Engine™Beta

Works fine on JSFiddle: http://jsfiddle.net/E6bn9/2/

Well, I was doing it without bind (just

  1. this.img.onload = this.imageLoaded;

but it was not working so some guy gave me advice to to use bind. I looked it up but I can't make it work properly :( .

Works fine on JSFiddle: http://jsfiddle.net/E6bn9/2/

Lol...apparently problem was somewhere else. Thanks for pointing out, it is working properly now :)

This topic is closed to new replies.

Advertisement