Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
Arjen van Heck Avatar asked May 18 '12 12:05

Arjen van Heck


People also ask

How do I create a dynamic canvas?

To dynamically create HTML5 canvas with JavaScript, we can use the createElement method. const canvas = document. createElement("canvas"); canvas.id = "canvas"; canvas. width = 1224; canvas.

Is HTML5 canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.

Does HTML5 support canvas element?

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.


2 Answers

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

Just do the following:

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);
like image 111
VisioN Avatar answered Oct 04 '22 09:10

VisioN


Via Jquery:

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

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

like image 43
Razan Paul Avatar answered Oct 04 '22 08:10

Razan Paul