HTML5 Canvas dynamisch erstellen


74

Hallo, ich habe eine Frage zum dynamischen Erstellen einer Zeichenfläche mit Javascript.

Ich erstelle eine Leinwand wie folgt:

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, erhalte ich einen nullWert:

cursorLayer = document.getElementById("CursorLayer");

Mache ich es falsch Gibt es eine bessere Möglichkeit, eine Leinwand mit JavaScript zu erstellen?


Antworten:


120

Das Problem ist, dass Sie Ihr Canvas-Element nicht in den Dokumentkörper einfügen.

Gehen Sie einfach wie folgt vor:

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);


10
oder einfach verwenden document.body.appendChild(canvas)(Sie müssen nicht mit getElementsByTagName danach suchen) - es ist eine Eigenschaft des Dokumentobjekts.
Gerrat

@Gerrat Guter Fang. Vielen Dank! Beide Möglichkeiten sind jedoch möglich.
VisioN

danke funktioniert super !! Nur ich muss 7 Minuten warten, bevor ich Ihre Antwort akzeptieren kann. lol xD
Arjen van Heck

Wie geht das ohne Anhängen? wie document.write auf aktuelle Position?
31авел Иванов

wie man Leinwand an ein bestimmtes div anhängt $ ("div"). appendChild (Leinwand) ist das möglich
kannan DS


1

Dies geschieht, weil Sie es aufrufen, bevor DOM geladen wurde. Erstellen Sie zuerst das Element und fügen Sie ihm Attribute hinzu. Rufen Sie es dann nach dem Laden von DOM 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");
}

Dies ist falsch, das Erstellen eines neuen Elements löst kein window.onload aus ...
pasx

Dies ist nicht der Fall, aber Sie können nach dem Erstellen keine zu schnellen Elemente aufrufen. Wenn Sie ein Element erstellen und es aufrufen, wird null zurückgegeben. Wenn Sie jedoch etwas warten oder window.onload hinzufügen, wird HTMLElement zurückgegeben.
Goblin01

OK, ich verstehe besser, worum es dir geht. Es ist im Kontext einer geladenen Seite sinnvoll, aber ich habe es im Kontext einer bereits geladenen Seite getestet.
Pasx

-1
 <html>
 <head></head>
 <body>
 <canvas id="canvas" width="300" height="300"></canvas>
 <script>
  var sun = new Image();
  var moon = new Image();
  var earth = new Image();
  function init() {
  sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
  moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
  earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
  window.requestAnimationFrame(draw);
  }

  function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');

  ctx.globalCompositeOperation = 'destination-over';
  ctx.clearRect(0, 0, 300, 300);

  ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
  ctx.strokeStyle = 'rgba(0, 153, 255, 0.4)';
  ctx.save();
  ctx.translate(150, 150);

  // Earth
  var time = new Date();
  ctx.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * 
  time.getMilliseconds());
  ctx.translate(105, 0);
  ctx.fillRect(10, -19, 55, 31); 
  ctx.drawImage(earth, -12, -12);

   // Moon
  ctx.save();
  ctx.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * 
  time.getMilliseconds());
  ctx.translate(0, 28.5);
  ctx.drawImage(moon, -3.5, -3.5);
  ctx.restore();

  ctx.restore();

   ctx.beginPath();
   ctx.arc(150, 150, 105, 0, Math.PI * 2, false);
   ctx.stroke();

   ctx.drawImage(sun, 0, 0, 300, 300);

   window.requestAnimationFrame(draw);
    }

   init();
   </script>
   </body>
   </html>

-1

Alternative

Verwenden Sie ein Element, .innerHTML=das in modernen Browsern recht schnell ist

document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";


// TEST

var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);
canvas { border: 1px solid black }

Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.