Problem generating canvas using createElement

258 views
Skip to first unread message

mf030

unread,
Jul 13, 2009, 2:32:46 PM7/13/09
to google-excanvas
Hi,

does anyone has a working example how to generate a canvas element
using document.createElement? If the canvas is included directly in
the HTML code it works. But also a createElement("div").innerHTML =
"<canvas...</canvas>" fails.

Thanks for any ideas, Martin

Ryan Schmidt

unread,
Jul 13, 2009, 5:05:57 PM7/13/09
to google-...@googlegroups.com

On Jul 13, 2009, at 13:32, mf030 wrote:

> does anyone has a working example how to generate a canvas element
> using document.createElement? If the canvas is included directly in
> the HTML code it works. But also a createElement("div").innerHTML =
> "<canvas...</canvas>" fails.

Yes, here is an example that works (tested in IE 6, 7, 8):


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>dynamic canvas creation</title>
<!--[if IE]><script type="text/javascript"
src="excanvas_r3/excanvas.compiled.js"></script><![endif]-->
<script type="text/javascript"><!--
function make_canvas(container_id, canvas_id, width, height) {
var canvas = document.createElement('canvas');
canvas.id = canvas_id;
canvas.width = width;
canvas.height = height;
document.getElementById(container_id).appendChild(canvas);
if (!canvas.getContext) {
G_vmlCanvasManager.initElement(canvas);
canvas = document.getElementById(canvas.id);
}
return canvas;
}
function init() {
var width = 160;
var height = 160;
var canvas = make_canvas('my_container', 'my_canvas', width, height);
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.fillRect(0, 0, width, height);
}
// --></script>
</head>
<body onload="init()">

<div id="my_container"></div>

</body>
</html>


mf030

unread,
Jul 14, 2009, 4:22:49 AM7/14/09
to google-excanvas
Thanks, the example worked fine. It was the
G_vmlCanvasManager.initElement(canvas); that done the job.

Martin
Reply all
Reply to author
Forward
0 new messages