Excursion for dynamically created canvas elements

Excanvas "for enternet Explorer" works great for predefined canvas elements. But when it comes to creating canvas elements dynamically during a script, this will not work ...

Any ideas?

+5
source share
3 answers

From the documentation :

If you created your canvas element dynamically, the getContext method will not be added to the element. To make it work, you need to call initElement on the G_vmlCanvasManager Object.

var el = document.createElement('canvas');
G_vmlCanvasManager.initElement(el);
var ctx = el.getContext('2d');
+12
source

initElement, ie8, chrome ff. , .

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);
+8

, . IE , "", , canvas javascript, .

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 simply fool IE by creating something legal and causing canvas to initialize instead.

I used jquery to create an ajax GET for this html block, 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 javascript, after the ajax call has completed and the HTML is inserted, I am initializing my canvas. This is just an 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");
...

Now it works for me in both Firefox and IE7.

+4
source

All Articles