views:

296

answers:

2

When I try to execute this in jQuery I get $ctx.getContext is not a function in firebug.

var $ctx = $( '<canvas />', {width:'100', height:'100'} )
$widget.append($ctx)                                     
$ctx.getContext('2d')                                    

Any idea why I get this error? How do I dynamically create and initialize a canvas element?

+3  A: 

$ctx is a jQuery object. use $ctx[0].getContext('2d') to get the context

Scott Evernden
`var $ctx = $( '<canvas />', {width:'100', height:'100'} )[0].getContext('2d')`
Evan Carroll
that would assign $ctx the canvas context which is both confusing and not, I believe, what Evan is going for... he does need to collect the result of the getContext() call tho - so you're correct there...
Scott Evernden
@Evan, you jumped the append step now .. for a single liner try `$( '<canvas />', {width:'100', height:'100'} ).appendTo($widget)[0].getContext('2d')` but now you do not have a variable that is referencing your jquery object..
Gaby
@scott, it is Evan that posted the comment ;)
Gaby
@Gaby, thanks!!!
Evan Carroll
ah .. yes . d'oh
Scott Evernden
A: 

If using excanvas you will need to use the following so it works in IE.

var canvas = $ctx[0];

if (canvas.getContext == undefined) {
    return G_vmlCanvasManager.initElement(canvas).getContext("2d"); 
}

return canvas.getContext('2d')
Castrohenge