canvas를 사용해 방향키로 좌우 이동 조작할 수 있는 캐릭터를 만들어보았습니다. 움직이는 캐릭터의 이전 모습을 삭제하기 위해 배경과 캐릭터의 캔버스를 나누어 진행하였습니다.
canvas 캐릭터 방향키로 좌우 이동하기
목차
1. 구현 화면
2. 고려사항
- 하나의 캔버스만 사용할 시 이전 캐릭터의 그림들을 삭제하기 어려움
- 이전 캐릭터의 그림을 지우기 위해 해당 좌표를 clearRect로 지울 시 배경까지 같이 삭제되어 버림
- 따라서, 배경, 캐릭터를 레이어로 나누어 구현
- 배경은 바닥에, 캐릭터는 공중에 뜬 상태로 그려진다고 볼 수 있음
3. 구현
- 배경 이미지를 넣을 canvas, 캐릭터를 넣을 canvas 2개 생성
- 배경 canvas와 캐릭터 canvas가 겹쳐져야 하므로 상위 태그에는 relative, canvas에는 absolute 속성 부여
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- 배경 이미지를 넣을 canvas, 캐릭터를 넣을 canvas 2개 생성 -->
<!-- 배경 canvas와 캐릭터 canvas가 겹쳐져야 하므로 상위 태그에는 relative, canvas에는 absolute 속성 부여 -->
<div style="position: relative;">
<canvas id="background" style="position: absolute;"></canvas>
<canvas id="character" style="position: absolute;"></canvas>
</div>
<script src="maple.js"></script>
</body>
</html>
- 배경 canvas 지정
- 캐릭터 canvas 지정
- 배경 제작
- 배경 경로 불러오기
- 배경 이미지를 불러오면 배경 canvas에 그리기
- 이미지를 불러오는 과정에서 비율이 깨지지 않게 이미지의 가로, 세로 길이를 그대로 canvas에 지정
- 캐릭터 제작
- 캐릭터 경로 불러오기
- 캐릭터의 x 좌표 지정
- 캐릭터 불러오면 캐릭터 canvas에 그리기
- 캐릭터가 이동할 수 있는 반경은 배경 내부 이므로 배경 이미지의 가로, 세로 길이를 그대로 canvas에 지정
- canvas에서 키입력 이벤트 설정
- 캐릭터의 좌표가 0이하면 더이상 왼쪽으로 이동 못하게 제한
- "캐릭터의 x 좌표 값 + 캐릭터의 가로 길이"가 배경의 가로 길이보다 커질 시 더이상 오른쪽으로 이동 못하게 제한
// maple.js
// 배경 canvas 지정
const backgroundCanvas = document.getElementById("background");
const backCtx = backgroundCanvas.getContext("2d");
// 캐릭터 canvas 지정
const characterCanvas = document.getElementById("character");
const chaCtx = characterCanvas.getContext("2d");
// 배경 경로 불러오기
const port = new Image();
port.src =
"https://github.com/ka0824/ka0824.github.io/assets/79782594/e264a9fb-541b-4cd4-845b-947385a19cef";
// 배경 이미지를 불러오면 배경 canvas에 그리기
// 이미지를 불러오는 과정에서 비율이 깨지지 않기 위해 이미지의 가로, 세로 길이를 그대로 canvas에 적용
port.onload = function () {
backgroundCanvas.width = port.width;
backgroundCanvas.height = port.height;
backCtx.drawImage(port, 0, 0);
};
// 캐릭터 경로 불러오기
const mushroom = new Image();
mushroom.src =
"https://github.com/ka0824/ka0824.github.io/assets/79782594/1cac660c-db2c-46d0-af9a-ecfebe31b62d";
// 캐릭터의 x 좌표 지정
let mushroomX = 0;
// 캐릭터 불러오면 캐릭터 canvas에 그리기
// 캐릭터가 이동할 수 있는 반경은 배경 내부 이므로 배경 이미지의 가로, 세로 길이를 그대로 적용
mushroom.onload = function () {
characterCanvas.width = port.width;
characterCanvas.height = port.height;
chaCtx.drawImage(mushroom, mushroomX, 100, 40, 50);
};
// canvas에서 키입력 이벤트 설정
document.addEventListener("keydown", function (event) {
switch (event.key) {
case "ArrowLeft":
// 캐릭터의 좌표가 0 이하면 더이상 왼쪽으로 이동 못하게 제한
if (mushroomX <= 0) {
return;
}
// 이동 속도는 -10, 이동할 때 마다 이전 이미지 지워주기
mushroomX -= 10;
chaCtx.clearRect(0, 0, characterCanvas.width, characterCanvas.height);
chaCtx.drawImage(mushroom, mushroomX, 100, 40, 50);
return;
case "ArrowRight":
// 캐릭터의 가로축이 40이므로, '현재 캐릭터의 x 좌표 값 + 40'이 배경의 가로축보다 커지면 오른쪽으로 이동 못하게 제한
if (mushroomX + 40 >= characterCanvas.width) {
return;
}
mushroomX += 10;
chaCtx.clearRect(0, 0, characterCanvas.width, characterCanvas.height);
chaCtx.drawImage(mushroom, mushroomX, 100, 40, 50);
return;
default:
return;
}
});
4. 구현된 코드로 보기
'javascript > canvas' 카테고리의 다른 글
canvas로 간단 애니메이션 구현하기 (0) | 2023.10.09 |
---|---|
캔버스로 기본 도형(2d) 그리기 (0) | 2023.10.08 |