Подтвердить что ты не робот

HTML5 Динамически создавать холст

Привет, у меня есть вопрос о динамическом создании холста с помощью 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";

но когда я попытаюсь найти его, я получаю значение null:

cursorLayer = document.getElementById("CursorLayer");

Я делаю это неправильно? Есть ли лучший способ создать холст с помощью JavaScript?

4b9b3361

Ответ 1

Проблема заключается в том, что вы не вставляете свой элемент 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);