You may need to initialize the canvas depending on when it is created. You can do that by calling these lines -
After obtaining the "canvas" element in the top of the script:
// initialize if excanvas
if (typeof G_vmlCanvasManager !== 'undefined')
G_vmlCanvasManager.initElement(canvas);
// now this should work
var ctx = canvas.getContext('2d');
... continue code here...