HTML5动态创建Canvas

Arj*_*eck 62 html javascript canvas

您好,我有一个关于使用JavaScript动态创建画布的问题.

我创建一个像这样的画布:

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";
Run Code Online (Sandbox Code Playgroud)

但当我尝试找到它时,我得到一个null值:

cursorLayer = document.getElementById("CursorLayer");
Run Code Online (Sandbox Code Playgroud)

我做错了吗?有没有更好的方法来使用JavaScript创建画布?

Vis*_*ioN 97

问题是您没有在文档正文中插入canvas元素.

只需执行以下操作:

document.body.appendChild(canvas);
Run Code Online (Sandbox Code Playgroud)

例:

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

  • 或者只使用`document.body.appendChild(canvas)`(您不必使用getElementsByTagName搜索它) - 它是文档对象的属性. (9认同)