Kunci jawaban 17 Latihan Canvas.
17.1 Bentuk
Contoh trapesium, berlian, dan spiral (bentuk lain polanya mirip):
// Trapesium
cx.beginPath();
cx.moveTo(10, 60);
cx.lineTo(30, 20);
cx.lineTo(70, 20);
cx.lineTo(90, 60);
cx.closePath();
cx.stroke();
// Berlian (persegi diputar)
cx.save();
cx.translate(150, 40);
cx.rotate(Math.PI / 4);
cx.strokeRect(-15, -15, 30, 30);
cx.restore();
// Spiral
cx.beginPath();
for (let i = 0; i < 300; i++) {
let sudut = i * 0.15;
let jari = i * 0.12;
let x = 300 + Math.cos(sudut) * jari;
let y = 40 + Math.sin(sudut) * jari;
if (i == 0) cx.moveTo(x, y);
else cx.lineTo(x, y);
}
cx.stroke();Kenapa: trapesium cuma empat titik lineTo lalu closePath + stroke. Berlian = persegi biasa yang di-rotate 45° (Math.PI/4); save/restore mengurung transformasinya supaya gak memengaruhi gambar lain. Spiral: di tiap langkah sudut dan jari-jari naik bersama, dan titik (cos·jari, sin·jari) makin jauh dari pusat sambil berputar. Zigzag dan bintang idenya sama — loop yang menghitung koordinat tiap titik.
→ Soal: 17 Latihan Canvas > 17.1 Bentuk
17.2 Bagan Pai
let total = data.reduce((jml, d) => jml + d.jumlah, 0);
let sudut = 0;
let pusatX = 100, pusatY = 100, jari = 90;
for (let d of data) {
let sudutBaru = sudut + (d.jumlah / total) * 2 * Math.PI;
cx.beginPath();
cx.moveTo(pusatX, pusatY);
cx.arc(pusatX, pusatY, jari, sudut, sudutBaru);
cx.fillStyle = d.warna;
cx.fill();
sudut = sudutBaru;
}Kenapa: total dihitung dulu dengan reduce. Tiap potongan menempati sudut sebesar porsinya dari lingkaran penuh ((jumlah/total) * 2π). moveTo ke pusat, arc menggambar busur dari sudut ke sudutBaru, lalu fill — membentuk juring. sudut diperbarui jadi sudutBaru untuk potongan berikutnya.
→ Soal: 17 Latihan Canvas > 17.2 Bagan Pai
17.3 Bola Memantul
let x = 100, y = 100, dx = 3, dy = 2, r = 12;
let lebar = 300, tinggi = 200;
function frame() {
cx.clearRect(0, 0, lebar, tinggi);
cx.strokeRect(0, 0, lebar, tinggi);
x += dx; y += dy;
if (x - r < 0 || x + r > lebar) dx = -dx;
if (y - r < 0 || y + r > tinggi) dy = -dy;
cx.beginPath();
cx.arc(x, y, r, 0, 2 * Math.PI);
cx.fillStyle = "blue";
cx.fill();
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);Kenapa: tiap frame seluruh canvas dibersihkan (clearRect) lalu digambar ulang — kotak dan bola. Posisi bola bertambah kecepatan tiap langkah. Kalau tepi bola menyentuh dinding (per sumbu), tanda kecepatan dibalik (dx = -dx) sehingga memantul. Ini fisika per-sumbu yang sama seperti game platform, cuma lebih sederhana (tanpa gravitasi).