Page 1 of 1

Mit Canvas-Ereignis-Listenern können keine Rechtecke im HTML-Canvas gezeichnet werden

Posted: 27 Jan 2025, 07:33
by Guest
Ich zeichne ein Rechteck in die Leinwand und erhalte den Kontext als funktionales Argument, wie Sie in der Draw -Funktion sehen können. Wenn ich versuche, ein Rechteck mit dem Kontext zu zeichnen, funktioniert es einwandfrei, aber wenn die Leinwand einen Ereignishörer hat und ich Logik zum Zeichnen des Mauszugs schreibe, funktioniert es nicht. Funktion < /p>

Code: Select all

  async draw(
ctx: OffscreenCanvasRenderingContext2D,
{ width, height }: { width: number; height: number }
) {
this.canvas = document.getElementById("player") as HTMLCanvasElement;
this.ctx = ctx;
this.ctx.globalCompositeOperation = "source-over";
this.ctx.fillStyle = "red";
this.ctx.fillRect(0, 0, 100, 100);

for (let i = 0; i < 100; i++) {
this.ctx.fillStyle = "red";
this.ctx.fillRect(100 + i, 200 + i, 100, 100);
}

console.log("Context draw", this.ctx);
this.addEventListeners();
}
< /code>
Mausbewegungsereignis < /p>
  handleMouseMove( event: MouseEvent) {
if (!this.drawing) return;

const rect = this.canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;

this.ctx.fillStyle = "red";
this.ctx.fillRect(x, y, 50, 50); // Draw rectangle
console.log("Mouse move at:", x, y, this.ctx);
}
Hier können Sie das gezeichnete Bild im Schleifenabschnitt sehen
Image