Add canvas to a page with javascript

nick2k3 picture nick2k3 · Feb 5, 2012 · Viewed 88.2k times · Source

I am trying to use Javascript in order to add a canvas to one page which originally does not have one. I am trying to do the following:

var canv=document.createElement("canvas");
canv.setAttribute("id", "canvasID");
alert(canv.id);
var c=document.getElementById("canvasID");
alert(c.id);

The problem is the the first alert(canv.id) results in canvasID, while the second alert is undefined because c is null.

Can anybody tell me what am I doing wrong?

PS: the code is designed to run under Greasemonkey so adding the canvas and its ID in the HTML itself is not a viable option.

Answer

Wouter J picture Wouter J · Feb 5, 2012

Use something like Node.appendChild( child ) for adding it to the DOM:

var canv = document.createElement('canvas');
canv.id = 'someId';

document.body.appendChild(canv); // adds the canvas to the body element
document.getElementById('someBox').appendChild(canv); // adds the canvas to #someBox

Or you can use element.innerHTML:

document.body.innerHTML += '<canvas id="someId"></canvas>'; // the += means we add this to the inner HTML of body
document.getElementById('someBox').innerHTML = '<canvas id="someId"></canvas>'; // replaces the inner HTML of #someBox to a canvas