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?
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.
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.
The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.
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);
Via Jquery:
$('<canvas/>', { id: 'mycanvas', height: 500, width: 200});
http://jsfiddle.net/8DEsJ/736/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With