
우주배경은 canvas 이용하여 랜덤 별자리 생성,
블랙홀 이미지는 keyframe 이용하여 무한 rotate
고양이이미지도 같이 rotate
고양이 이미지 클릭 시 클릭된 고양이를 없애고
safezone에 같은 data-id의 고양이 생성
safezone에 있는 고양이 수 체크하여 몇마리 남았는지 보여주기
우주배경에 맞는 반짝이는 전광판 디자인 텍스트
[ 필요한 값 ]
(간단히 소개하는 소스이므로 정확한 전체 소스는 github에서 확인해주세요!)
canvas 태그를 이용한 배경생성
<canvas id="canvas"></canvas>
<style>
canvas {
width: 100%;
height: 100%;
background: rgb(12, 3, 32);
display: block;
margin: 0 auto;
position: absolute;
z-index: -5;
}
</style>
<script>
//우주배경 캔버스
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//화면사이즈
var screenX = $(window).width(); //실제화면가로
var screenY = $(window).height(); //실제화면세로
//랜덤 숫자 함수
function randomNum(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
//별 그리기
function draw() {
var x = randomNum(0, screenX);
var y = randomNum(0, screenY);
var r = randomNum(1, 2);
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 1);
ctx.fillStyle = 'white';
ctx.fill();
}
var starTotal = 150;
for (var i = 0; i < starTotal; i++) {
draw();
}
</script>
블랙홀을 돌릴 keyframe (github에는 크로스 브라우징 반영함)
<style>
.circle {
animation: circle 1s linear infinite;
}
@keyframes circle {
0% {transform: rotate(0deg);}
100% {transform: rotate(360deg);}
}
</style>
전광판 디자인 keyframe (github에는 크로스 브라우징 반영함)
<style>
.neonText {
animation: neon 1.5s infinite alternate;
color: #fff;
}
@keyframes neon {
0%, 18%, 22%, 25%, 53%, 57%, 100% {
text-shadow:
0 0 4px #fff,
0 0 11px #fff,
0 0 19px #fff,
0 0 40px rgb(255, 0, 238),
0 0 80px rgb(255, 0, 238),
0 0 90px rgb(255, 0, 238),
0 0 100px rgb(255, 0, 238),
0 0 150px rgb(255, 0, 238);
}
20%, 24%, 55% {
text-shadow: none;
}
}
</style>
고양이를 클릭할 경우, safezone에 고양이 생성
<script>
$('.space-cat').on('click', function (e) {
var catNum = e.target.dataset.id; //클릭한 고양이 data-id값
var cloneCat = `#cat${catNum}`; //새 클론 고양이 id값
//고양이 세이프존 위치값
var position = [
{ id: 0, left: 0, top: 0 },
{ id: 1, left: '10%', top: '0%' },
{ id: 2, left: '5%', top: '30%' },
{ id: 3, left: '10%', top: '70%' },
{ id: 4, left: '75%', top: '0%' },
{ id: 5, left: '80%', top: '30%' },
{ id: 6, left: '75%', top: '65%' },
]
//기존 고양이 가리기
$(e.target).addClass('hidden');
//safe-zone에 똑같은 id의 고양이 추가
$('.safe-zone').prepend(`<img src="images/space_cat_${catNum}.png" id="cat${catNum}" class="space-cat up-down" draggable="false" width="120" data-id="${catNum}">`)
//화면상 애니메이션
$(cloneCat).animate({
left: `${position[catNum].left}`,
top: `${position[catNum].top}`
}, {
duration: 2000,
fill: "forwards"
});
});
</script>
구해야하는 고양이 몇 마리인지 체크
<script>
//위험한 고양이 합계
var total = $('.danger-zone').find('.space-cat').length;
function totalCount() {
$('.danger-num').html(total);
return false;
}
totalCount();
//safezone에 몇마리 고양이 있는지 체크
if ($('.safe-zone').find(cloneCat)) {
//고양이 숫자 바꾸기
var howMany = $('.safe-zone').find('.space-cat').length;
$('.safe-num').html(howMany); //안전한 고양이 숫자변경
$('.danger-num').html(total - howMany); //위험한 고양이 숫자변경
//게임성공 문구띄우기
if ($('.danger-num').html() == 0) { //위험한 고양이가 0인경우
setTimeout(successAlert, 1000);
}
}
</script>
*** 해당부분의 주석만 표시함
모바일에서 두번이상 짧게 터치되면 확대되는 동작 막기(더블탭막기)
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<script>
document.documentElement.addEventListener('touchstart', function (event) {
if (event.touches.length > 1) { //----- 두손가락이 아닌 한손가락 체크
event.preventDefault();
}
}, false);
var lastTouchEnd = 0;
document.documentElement.addEventListener('touchend', function (event) {
var now = (new Date()).getTime();
if (now - lastTouchEnd <= 300) { //----- 300ms 보다 짧게 터치될 경우 더블탭막기
event.preventDefault();
} lastTouchEnd = now;
}, false);
</script>
첫번째 유효클릭 체크하기
<script>
var num = 0; //----클릭 수 체크
$('.space-cat').on('click', function (e) {
var catNum = e.target.dataset.id;
var cloneCat = `#cat${catNum}`;
num++;
if (num == 1) { //----클릭수가 1일 경우만 동작
function moveSafeZone(e) {
$(e.target).addClass('hidden');
$('.safe-zone').prepend(`<img src="images/space_cat_${catNum}.png" id="cat${catNum}" class="space-cat up-down" draggable="false" width="120" data-id="${catNum}">`)
$(cloneCat).animate({
left: `${position[catNum].left}`,
top: `${position[catNum].top}`
}, {
duration: 2000,
fill: "forwards"
});
}
moveSafeZone(e);
if ($('.safe-zone').find(cloneCat)) {
$(cloneCat).css('cursor', 'auto');
var howMany = $('.safe-zone').find('.space-cat').length;
$('.safe-num').html(howMany);
$('.danger-num').html(total - howMany);
if ($('.danger-num').html() == 0) {
setTimeout(successAlert, 1000);
}
num = 0; //----클릭수 초기화
}
}
});
</script>


js로 html을 조작하는 부분이 많았던 프로젝트!
게임의 난이도에 비해 개발은 간단했다
keyframe이 많이 들어있어서 크로스브라우징에 더욱 신경썼는데
블로그에 올리기엔 소스가 길어져서 github에는 반영해놓았음
그리고 미친듯한 클릭과 터치를 하게되는 프로젝트라
유효클릭과 더블탭막기도 추가해놓았다
canvas 는 mdn문서를 보며 처음 사용해봤는데
새롭기도하고 꽤 흥미로워서 다음에 canvas를 이용한 프로젝트도
한번 생각해봐야겠다