Aufgabenstellung "AFFE"
Beispiel für Zeichnen auf dem Canvas. Zeige, dass Du mit Koordinaten, Variablen, Funktionen, Schleifen und Zufallszahlen umgehen kannst.
HTML
<h1>Aufgabenstellung</h1>
<p>Schreibe ein Programm, das 10mal das Wort "AFFE" zeichnet,
und zwar an zufälliger Position</p>
<canvas id="c"></canvas>
<p>Tipp: Das Koordinatensystem des Canvas startet links oben.</p>
<p>Tipp: Drücke links oben auf "Run" und das vorhandene Programm neu zu starten.</p>
CSS
#c {
background-color: white
}
body {
background-color: #ddd;
}
JavaScript
var my_canvas = document.getElementById("c");
var my_context = my_canvas.getContext("2d");
my_canvas.width = 250;
my_canvas.height = 250;
//
// eine Funktion die ein A zeichnet
// als argumente:
// x1,y1 ist das linke obere Eck,
// i ist die Zeilenhöhe.
function a(x1, y1, i) {
my_context.moveTo(x1, y1+i);
my_context.lineTo(x1, y1);
my_context.lineTo(x1+i/2, y1);
my_context.moveTo(x1, y1+i/2);
my_context.lineTo(x1+i/4, y1+i/2);
my_context.stroke();
}
//
// a aufrufen und an einer fixen position zeichnen
//
a(150,50,30);
//
// zwei zufallszahlen zwischen 0 und 200 erzeugen
//
//x_zufall=Math.random()*200;
//y_zufall=Math.random()*200;
//
// a mit den zufalls-koordinaten aufrufen.
//
//a(x_zufall,y_zufall,50);