使用javascript将画布添加到页面

nic*_*2k3 36 javascript html5 canvas add html5-canvas

我正在尝试使用Javascript将画布添加到一个原本没有的画面.我正在尝试执行以下操作:

var canv=document.createElement("canvas");
canv.setAttribute("id", "canvasID");
alert(canv.id);
var c=document.getElementById("canvasID");
alert(c.id)?;
Run Code Online (Sandbox Code Playgroud)

问题是第一个警报(canv.id)导致canvasID,而第二个警报未定义,因为c为null.

谁能告诉我我做错了什么?

PS:代码设计为在Greasemonkey下运行,因此在HTML本身中添加画布及其ID不是一个可行的选择.

Wou*_*r J 54

使用类似的东西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
Run Code Online (Sandbox Code Playgroud)

或者您可以使用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
Run Code Online (Sandbox Code Playgroud)


小智 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
Run Code Online (Sandbox Code Playgroud)

我一直使用这个并且工作得很好......


Kev*_*nis 5

var canv=document.createElement("canvas");
canv.setAttribute("id", "canvasID");
document.body.appendChild(canv);
Run Code Online (Sandbox Code Playgroud)

没有像第三行这样的东西,你的新画布永远不会真正插入到页面中。