HTML5dynamic创buildcanvas

您好,我有一个关于dynamic创build一个使用JavaScript的canvas的问题。

我创build一个这样的canvas:

var canvas = document.createElement('canvas'); canvas.id = "CursorLayer"; canvas.width = 1224; canvas.height = 768; canvas.style.zIndex = 8; canvas.style.position = "absolute"; canvas.style.border = "1px solid"; 

但是当我试图find它,我得到一个null值:

 cursorLayer = document.getElementById("CursorLayer"); 

我做错了吗? 有没有更好的方式来创build使用JavaScript的canvas?

问题是,您不要将您的canvas元素插入到文档正文中。

只要做到以下几点:

 document.body.appendChild(canvas); 

例:

 var canvas = document.createElement('canvas'); canvas.id = "CursorLayer"; canvas.width = 1224; canvas.height = 768; canvas.style.zIndex = 8; canvas.style.position = "absolute"; canvas.style.border = "1px solid"; var body = document.getElementsByTagName("body")[0]; body.appendChild(canvas); cursorLayer = document.getElementById("CursorLayer"); console.log(cursorLayer); // below is optional var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgba(255, 0, 0, 0.2)"; ctx.fillRect(100, 100, 200, 200); ctx.fillStyle = "rgba(0, 255, 0, 0.2)"; ctx.fillRect(150, 150, 200, 200); ctx.fillStyle = "rgba(0, 0, 255, 0.2)"; ctx.fillRect(200, 50, 200, 200); 

通过Jquery:

 $('<canvas/>', { id: 'mycanvas', height: 500, width: 200}); 

http://jsfiddle.net/8DEsJ/736/