HTML5 dynamically create canvas

Hi, 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 find it, I get null :

 cursorLayer = document.getElementById("CursorLayer"); 

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

+42
javascript html html5 canvas
May 18 '12 at 12:18
source share
2 answers

The problem is that you are not inserting your canvas element into the body of the document.

Just follow these steps:

 document.body.appendChild(canvas); 

Example:

 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"; var body = document.getElementsByTagName("body")[0]; body.appendChild(canvas); cursorLayer = document.getElementById("CursorLayer"); console.log(cursorLayer); // below is optional var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgba(255, 0, 0, 0.2)"; ctx.fillRect(100, 100, 200, 200); ctx.fillStyle = "rgba(0, 255, 0, 0.2)"; ctx.fillRect(150, 150, 200, 200); ctx.fillStyle = "rgba(0, 0, 255, 0.2)"; ctx.fillRect(200, 50, 200, 200); 
+58
May 18 '12 at 12:22
source share

Via jQuery:

 $('<canvas/>', { id: 'mycanvas', height: 500, width: 200}); 

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

+1
Jul 17 '15 at 0:26
source share



All Articles