Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

html - Add canvas to a page with javascript

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...