Canvas + Rect + Line

Beispiel für das Zeichnen auf dem Canvas

by bjelline

HTML

<h1>Zeichnen auf dem Canvas</h1>
<canvas id="canv"></canvas>

<p>Das Koordinatensystem des Canvas beginnt links oben.</p>

CSS

#canv { 
    background-color: white 
}
body {
    background-color: #ddd;
}

JavaScript

var v = document.getElementById("canv");
v.width = 250;
v.height = 250;

var c = v.getContext("2d"); // c ist der "drawing context"
// mit dem arbeiten wir ab jetzt

// Beispiel für eine blaue Linie
c.beginPath();
c.moveTo(0, 0);
c.lineTo(240, 20);
c.strokeStyle = "rgb(0,0,200)";
c.stroke();
c.closePath();

// Beispiel für ein rotes rechteck
c.fillStyle = "rgb(200,0,0)";
c.fillRect(80, 60, 90, 15);

// Beispiel für eine Schleife
// die mehrere grüne Linien zeichnet
c.beginPath();
for (var x = 0; x <= v.width; x += 25) {
    // mittelpunkt des ganzen canvas
    c.moveTo(v.width / 2, v.height / 2);
    // punkt am unteren rand des canvas
    c.lineTo(x, v.height);
}
c.strokeStyle = "rgb(0,200,0)";
c.stroke();
c.closePath();