Arjen van Heck Arjen van Heck - 6 months ago 47
HTML Question

HTML5 Dynamically create Canvas

Hi there i have a question about dynamically creating a canvas using javascript.

i create a canvas like this:

var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
canvas.width = 1224;
canvas.height = 768;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";


but when I try to locate it, I get a
null
value:

cursorLayer = document.getElementById("CursorLayer");


Am I doing it wrong? Is there a better way to create a canvas using JavaScript?

Answer

The problem is that you do not insert your canvas element in the document body.

Just do the following:

document.body.appendChild(canvas);

DEMO: http://jsfiddle.net/8DEsJ/