簡體   English   中英

使用javascript將畫布添加到頁面

[英]Add canvas to a page with javascript

我正在嘗試使用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不是一個可行的選擇。

使用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
    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

我一直使用這個並且工作得很好......

var canv=document.createElement("canvas");
canv.setAttribute("id", "canvasID");
document.body.appendChild(canv);

沒有像第三行那樣的東西,你的新畫布實際上從未插入到頁面中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM