Kleiner JavaScript Kurs

Canvas Grundlagen

Um auf einer HTML - Seite zu zeichnen benötigen wir eine Zeichenfläche (Canvas, besser zu sehen mit Rahmen)

<body>
    <canvas id="myCanvas" width="480" height="320" style="border:2px solid #000000;">
    </canvas>
</body>

Mit JavaScript können wir auf dieser Zeichenfläche zeichnen. Hier einige Möglichkeiten:
<script>
    //Canvas als Zeichenfläche festlegen (Variable canvas und ctx);
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    //Breite der Zeichenfläche: (480);
    var breite = canvas.width;
    //Höhe der Zeichenfläche: (320);
    var hoehe = canvas.height;
</script>
Linie, Rechteck, Kreis und Text:

    //Linie;
    //1. Startpunkt festlegen: moveTo(x,y);
    //2. Endpunkt: lineTo(x,y);
    //3. Zeichnen: stroke();
    ctx.moveTo(0, 0);
    ctx.lineTo(200, 100);
    ctx.stroke();
    //Rechteck: rect(xPos, yPos, Breite, Höhe);
    ctx.rect(50,50,150,30);
    ctx.stroke();
    //Kreis / Kreisbogen:;
    //1. PfadBeginn: beginPath();
    //2. arc(xMitte, yMitte, Radius, Startwinkel, Endwinkel in Bogenmaß); 
    ctx.beginPath();
    ctx.arc(240, 160, 60, 0, Math.PI*2);
    ctx.stroke();
    //Text: fillText("Text", xPos, yPos);
    ctx.fillText("Punktestand", 20, 300);
 

Formatierungen:
Linienfarbe: strokeStyle = "#FF0000";
Linienbreite: lineWidth = 5;

ctx.strokeStyle = "#FF0000";
ctx.lineWidth = 5;
ctx.rect(50,50,150,30);
ctx.stroke();

Fläche füllen:
Start: beginPath();
Zeichnen: z.B. Kreis, Rechteck, Figur aus Linien
Füllart festlegen: fillStyle = "#0095DD";
und füllen: fill();
Ende (ersetzt stroke(): closePath();

ctx.beginPath();
ctx.rect(50,50,150,30);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();

Ausgefüllte Rechtecke können auch mit der Funktion
fillRect( )
gezeichnet werden:

ctx.fillStyle = "yellow";
ctx.fillRect(50,50,100,100);