MrFish Posted March 15, 2011 Share Posted March 15, 2011 I'm trying to make an animated gif class for the new html canvas. I start out by loading a bunch of images to the class and calling the start() function. This function does a setInterval function to call a run() function every second. But I can't get the function run to call any variables inside the class. They will all come up "undefined" or "NaN" function AnimatedGif(){ //Variables this.frames = new Array(); this.frameDuration = 1000; this.image = new Image(); this.frame = 0; this.runInterval; this.loadImage = function(url) { fl = this.frames.length; img = new Image(); img.src=url; this.frames[fl] = img; } this.start = function() { this.runInterval = setInterval(this.run, this.frameDuration) } this.stop = function() { this.clearInterval(this.runInterval); } this.run = function() { frame = this.frame; //This is undefined at first, then NaN frames = this.frames; frameLength = frames.length; this.image = frames[frame]; this.frame++; if(this.frame == frameLength) { this.frame = 0; } }} I've tried putting this.run in double quotes but then it won't even run. Link to comment Share on other sites More sharing options...
thescientist Posted March 15, 2011 Share Posted March 15, 2011 you should try declaring your local variable with the var keyword. did you try it as "this.run()"?it's most likely a scope issue with this and what it references within the setinterval function. you coudl trying something like this: this.start = function(){ var ref = this; this.runInterval = setInterval(ref.run, ref.frameDuration);}; Link to comment Share on other sites More sharing options...
justsomeguy Posted March 15, 2011 Share Posted March 15, 2011 In order to specify the scope that the function runs in, one easy way is to add a createDelegate method to functions with this code: Function.prototype.createDelegate = function(obj, args){ var method = this; return function() { var callArgs = args || arguments; return method.apply(obj || window, callArgs); };} Then use this:this.runInterval = setInterval(this.run.createDelegate(this), this.frameDuration)That will make sure that when the function executes, this is set to the same object, or it's running in the same scope. Link to comment Share on other sites More sharing options...
MrFish Posted March 15, 2011 Author Share Posted March 15, 2011 That did it justsomeguy. Thanks for your help! Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.