Hallo, ich habe eine Frage zum dynamischen Erstellen einer Leinwand mit Javascript.
ich erstelle so eine Leinwand:
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";
aber wenn ich versuche, es zu finden, bekomme ich einen null
-Wert:
cursorLayer = document.getElementById("CursorLayer");
Mache ich es falsch? Gibt es eine bessere Möglichkeit, eine Leinwand mit JavaScript zu erstellen?
Das Problem ist, dass Sie Ihr Canvas-Element nicht in den Dokumentkörper einfügen.
Mach einfach folgendes:
document.body.appendChild(canvas);
Beispiel:
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);
Über Jquery:
$('<canvas/>', { id: 'mycanvas', height: 500, width: 200});
Versuchen
document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";
var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);
canvas { border: 1px solid black }
Dies geschieht, weil Sie es aufrufen, bevor DOM geladen wurde. Erstellen Sie zuerst das Element und fügen Sie Attribute hinzu. Nachdem DOM geladen hat, rufen Sie es auf. In Ihrem Fall sollte es so aussehen:
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";
window.onload = function() {
document.getElementById("CursorLayer");
}