Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excanvas for dynamically created canvas elements

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??

like image 494
user192318 Avatar asked Oct 28 '09 06:10

user192318


3 Answers

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');
like image 115
Matthew Crumley Avatar answered Nov 14 '22 14:11

Matthew Crumley


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);
like image 32
Jeff Lamb Avatar answered Nov 14 '22 13:11

Jeff Lamb


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.

like image 4
Mnebuerquo Avatar answered Nov 14 '22 13:11

Mnebuerquo