0

I want to call to method setupCanvas.Draw(); to draw rectangle.

And for some reason I can not call a function Draw(); from out the scop game.setupCanvas(); Demo jsfiddle

window.game = window.game|| {};
game.main = function() {};      
game.setupCanvas = function(){

        var w = $(window).outerWidth();
        var h = $(window).outerHeight();
        myCanvas = document.createElement('canvas');
        document.body.appendChild(myCanvas);
        myCanvas.id     = "playground";
        myCanvas.width  = w * 0.8;
        myCanvas.height = h * 0.8;
        myCanvas.style.left= (w - myCanvas.width )/2 + 'px' ;
        myCanvas.style.top= (h -  myCanvas.height )/2 + 'px' ;     
        myCanvas.style.zIndex   = 10;
        myCanvas.style.position = "absolute";
        myCanvas.style.border   = "1px solid green ";
        this.ctx= $('#playground').get(0).getContext('2d');

       this.Draw  = function(){
         ctx.fillStyle="#0000FF";
         ctx.fillRect(150,75,150,75);
         ctx.fillStyle="#F0F0FF";
         ctx.fillRect(0,0,150,75);
    };
}();    
    game.setupCanvas.Draw();

​

Many thanks

2 Answers 2

2

You need to create a new instance:

var x = new game.setupCanvas();

x.Draw();

Also, this part is wrong:

 };
}(); // <--

game.setupCanvas.Draw();

You're immediately-invoking the function, which you shouldn't be doing. It returns undefined to game.setupCanvas. Take it away and your code should work.

Moreover, when you reference a thectx property in your Draw method, you need to use this.ctx.

jsFiddle Demo

Sign up to request clarification or add additional context in comments.

3 Comments

@limelights You need to get rid of the () at the end of the function expression to game.setupCanvas
Yeah, I missed it. Also, he'll get a undefined on ctx since he's not referring to the this.ctx. You should update your answer! :)
@rotem Why are you changing it now? It works like this -- jsfiddle.net/eEfJ7
0

Your assignment of game.setupCanvas is invalid since the self invoking function doesn't return anything so game.setupCanvas will be undefined. Make sure to return an object with your public methods like this.

return {
    Draw: function(){
      ctx.fillStyle="#0000FF";
      ctx.fillRect(150,75,150,75);
      ctx.fillStyle="#F0F0FF";
      ctx.fillRect(0,0,150,75);
    },
    DrawSomethingElse: function(){
      ctx.fillStyle="#0000FF";
      ctx.fillRect(150,75,150,75);
      ctx.fillStyle="#F0F0FF";
      ctx.fillRect(0,0,150,75);
    }
};

Here is an update to your fiddle http://jsfiddle.net/dAvtS/11/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.