Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery dynamic canvas creation, $ctx.getContext is not a function

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?

like image 662
NO WAR WITH RUSSIA Avatar asked Jul 13 '10 17:07

NO WAR WITH RUSSIA


2 Answers

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

like image 91
Scott Evernden Avatar answered Oct 21 '22 06:10

Scott Evernden


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')
like image 1
Castrohenge Avatar answered Oct 21 '22 06:10

Castrohenge