Excanvas for dynamically created canvas elements

11.5k views Asked by At

Excanvas "for enternet Explorer" is working fine for predefined canvas elements. But when it comes to creating canvas elements dynamically during the script, it will not work...

Any ideas??

3

There are 3 answers

2
Matthew Crumley On

From the documentation:

If you have created your canvas element dynamically it will not have the getContext method added to the element. To get it working you need to call initElement on the G_vmlCanvasManager object.

var el = document.createElement('canvas');
G_vmlCanvasManager.initElement(el);
var ctx = el.getContext('2d');
0
Jeff Lamb On

I append it to the document before calling initElement and it works for ie8, chrome, and ff. Took me a while to figure it out.

var foo = document.getElementById("targetElementID");
var canvas = document.createElement('canvas');
canvas.setAttribute("width", 620);
canvas.setAttribute("height", 310);
canvas.setAttribute("class", "mapping");
foo.appendChild(canvas);
canvas = G_vmlCanvasManager.initElement(canvas);
0
Mnebuerquo On

I think I've found the trick to this. IE doesn't know what a "canvas" is, so when you create a canvas element with your javascript, it doesn't work.

Other examples I've seen do this to create their canvas:

var el = document.createElement('canvas');//this doesn't work in IE

So the trick is to just fool IE by creating something legal and calling the canvas initialization on it instead.

I used jquery to do an ajax GET for this block of html which I then inserted into the DOM:

<div id="canvasholder">
    <canvas id="mycanvas" width="1024" height="768" style="width:1024px;height:768px"></canvas>
</div>

In the javascript after the ajax call has completed and the HTML is inserted, I do my canvas initialization. This is just the interesting snippet from my init function.

...
canvas = $('#mycanvas').get(0);//get dom element from jquery
if(!canvas.getContext)//function doesn't exist yet
{
//we're in IE if we reach this block
//otherwise getContext already exists
$('#canvasholder').empty();
//add #mycanvas as a div instead of a canvas
//you could use document.createElement('div') instead of jquery
$('#canvasholder').append(
    '<div id="mycanvas" width="1024" height="768"></div>');
canvas = $('#mycanvas').get(0);
if(typeof G_vmlCanvasManager  != 'undefined' )
{
    canvas = G_vmlCanvasManager.initElement(canvas);
}
}
//now you're set up to draw!
context = canvas.getContext("2d");
...

This is now working for me in both Firefox and IE7.