我正在尝试使用Javascript将画布添加到最初没有画布的页面。 我正在尝试执行以下操作:
var canv=document.createElement("canvas");
canv.setAttribute("id", "canvasID");
alert(canv.id);
var c=document.getElementById("canvasID");
alert(c.id);
问题是第一个警报(canv.id)导致canvasID,而第二个警报未定义,因为c为null。
有谁可以告诉我,我做错了什么?
PS:代码设计为在Greasemonkey下运行,因此在HTML本身中添加画布及其ID不是一个可行的选择。
答案 0 :(得分:52)
使用类似Node.appendChild( child )
的内容将其添加到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
或者您可以使用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
答案 1 :(得分:6)
var canvas = document.getElementById('canvas'); //finds Original Canvas
img = document.createElement('img');
img.src = 'images/a.jpg'; //stores image src
var canv = document.createElement('canvas'); // creates new canvas element
canv.id = 'canvasdummy'; // gives canvas id
canv.height = canvas.height; //get original canvas height
canv.width = canvas.width; // get original canvas width
document.body.appendChild(canv); // adds the canvas to the body element
var canvas1 = document.getElementById('canvasdummy'); //find new canvas we created
var context = canvas1.getContext('2d');
context.drawImage(img, 0, 0, canvas.width, canvas.height); //draws background image
context.drawImage(canvas, 0, 0); //draws original canvas on top of background
cscreen = canvas1.toDataURL(); //generates PNG of newly created canvas
document.body.removeChild(canv); // removes new canvas
我一直使用这个并且效果很好......
答案 2 :(得分:3)
var canv=document.createElement("canvas");
canv.setAttribute("id", "canvasID");
document.body.appendChild(canv);
如果没有类似第三行的内容,您的新画布实际上永远不会插入到页面中。