Sahne ve oyuncu
Canvas 2D bağlamında bir sahne ve oyuncu çizimini kurarsın.
Oyuncu dikdörtgeni
Sahnedeki nesneleri JavaScript nesneleri olarak tutarız. player nesnesi dört özellik taşır: x ve y sol üst köşenin koordinatı, width ve height ise boyutları.
Örneğin { x: 180, y: 120, width: 40, height: 40 } 40x40 piksellik bir kareyi (180, 120) noktasına yerleştirir. Canvasın orijini sol üst köşededir; y ekseni aşağı doğru artar.
Çizim döngüsü
Her karede önce ctx.clearRect(0, 0, canvas.width, canvas.height) ile sahneyi temizleriz. Sonra ctx.fillRect(player.x, player.y, player.width, player.height) ile oyuncuyu çizeriz. Son olarak requestAnimationFrame(draw) ile bir sonraki kareyi isteriz.
Bu üç adım bir draw işlevinde toplanır ve draw() çağrısıyla döngü başlatılır. Temizle → çiz → tekrar iste.
Uygulama Sahne ve oyuncuyu çiz
player nesnesini { x: 180, y: 120, width: 40, height: 40 } olarak tanımla. Sonra draw işlevini ekle: önce ctx.clearRect ile sahneyi temizle, ctx.fillStyle ile "#2563eb" rengini ver, ctx.fillRect ile oyuncuyu çiz ve requestAnimationFrame(draw) ile döngüyü sürdür. Son olarak draw() çağrısıyla başlat.
Örnek çözümü göster
const player = { x: 180, y: 120, width: 40, height: 40 };
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#2563eb";
ctx.fillRect(player.x, player.y, player.width, player.height);
requestAnimationFrame(draw);
}
draw();
Kendini test et
-
fillStyle ile renk ata
ctx.fillStyle = ____;Cevabı göster
ctx.fillStyle = "#2563eb"; -
Hangi yöntem bir dikdörtgeni renkle doldurur?
- strokeRect()
- clearRect()
- fillRect()
- drawRect()
Cevabı göster
fillRect() — Doğru! fillRect(x, y, w, h) içini renkle doldurur.
-
Canvas yöntemlerini eşleştir
- clearRect
- Alanı temizle
- fillRect
- Dikdörtgen boya
- fillStyle
- Renk ata
- getContext
- Bağlamı al