<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>경로를 따라 사각형 그리기</title> </head> <body> <canvas id="myCanvas" width="600" height="400" style="border: 2px solid #cef"> </canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); let x = 50; let y = 50; let dx = 2; let dy = 2; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 화면 지우기 ctx.beginPath(); // 경로를 시작 ctx.moveTo(x, y); // 선을 그리지 않고 이동 ctx.lineTo(x + 50, y); // 선을 그리면서 이동 ctx.lineTo(x + 50, y + 50); ctx.lineTo(x, y + 50); ctx.closePath(); // 처음과 마지막 연결 ctx.strokeStyle = "blue"; ctx.stroke(); // 경로 그리기 ctx.fillStyle = "yellow"; ctx.fill(); // 경로 채우기 x = x + dx; y = y + dy; if (x + 50 > canvas.width || x < 0) dx = -dx; if (y + 50 > canvas.height || y < 0) dy = -dy; requestAnimationFrame(draw); } draw(); </script> </body> </html>