How to add a html5 CANVAS within a DIV

Just try this code and will work for you surely:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Game Stage</title>
<script type="text/javascript">
    function loadCanvas(id) {
        var canvas = document.createElement('canvas');
        div = document.getElementById(id); 
        canvas.id     = "CursorLayer";
        canvas.width  = 1224;
        canvas.height = 768;
        canvas.style.zIndex   = 8;
        canvas.style.position = "absolute";
        canvas.style.border   = "1px solid";
        div.appendChild(canvas)
    }
</script>
</head>
<body>
<header>
    <h1>The most important heading on this page</h1>
    <p>With some supplementary information</p>
</header>
<div id="divControls"></div>
<div id="divGameStage"></div>
<script type="text/javascript">
    loadCanvas("divGameStage");
</script>
</body>
</html>

Some things keep in mind:

  • Error No 1 is missing quotes in loadCanvas("divGameStage");
  • Error No 2 is syntax error div = document.getElementById(id); "..ID(id)" was in your code.

If then also it doesnt work then i am sure that you are testing it on Internet Explorer (specially < IE9)
If these is the case, FYI IE9 and above supports canvas no other lesser version supports canvas

Cheers!!!


You just have to append it to your <div> instead of the body:

<script type="text/javascript">
    function loadCanvas(id) {
        var canvas = document.createElement('canvas'),
            div = document.getElementById(id);
        canvas.id     = "canvGameStage";
        canvas.width  = 1000;
        canvas.height = 768;
        canvas.style.zIndex   = 8;
        canvas.style.position = "absolute";
        canvas.style.border   = "1px solid";
        div.appendChild(canvas);
    }
    /* ... */
    loadCanvas("divGameStage");
</script>

Quite simply :-)


<script type="text/javascript">
    function loadCanvas() {
        var canvas = document.createElement('canvas');
        canvas.id     = "canvGameStage";
        canvas.width  = 1000;
        canvas.height = 768;
        canvas.style.zIndex   = 8;
        canvas.style.position = "absolute";
        canvas.style.border   = "1px solid";
        var div = document.createElement("div");
        div.className = "divGameStage";
        div.appendChild(canvas);
        document.body.appendChild(div)
    }
</script>