Canvas - 공 오른쪽으로 이동시키기

조성현·2021년 7월 13일
0
post-thumbnail

🚨 주의사항

  1. requestAnimationFrame 에 대한
    이해가 부족한 상태에서 쓰는 글입니다.
  1. 이 글은 정말로 오른쪽으로만 이동시키고 끝납니다


🚦 삽질 정리

1. window.cancelAnimationFrame

  • 지금 와서 보니까 왜 헤멨는지 의문이 들 정도로
    추악한 삽질이라 notation만 남깁니다...

2. import 와 export

import Ball from './ball.js' --- (1)
import Ball from './ball' --- (2)

충격적이게도 (2)로 할 경우
class 가 import되지 않는다

export default를 쓰자.
왜 인지는 모르나, 맨아래에다가
export { ... } 하는 건 안되더라,,,

3. draw() 메소드

// ball.js
draw( 🚑 ){
        ctx.clearRect(0, 0, 800, 600)
        ctx.beginPath()
        ctx.arc(this.xpos, this.ypos, this.rad, 0, Math.PI * 2)
        ctx.fillStyle = 'steelblue'
        ctx.fill()
    }

parameter에 처음엔 void로 설정해줬고
main.js의 ctx를 export 해서
ball.js에서 쓰는 식으로 하려고 했는데

왜인지는 모르겠으나 받아내지를 못하더라...


구급차 자리에 .... ctx를 넣어주자

4. <script>...</script>

<script src="main.js"></script> --- (1)
<script type="module" src="main.js"></script> --- (2)

왜 인지는 모르지만 (1)처럼 하면 오류가 난다





👀 본론

main.js

// main.js


import Ball from './ball.js'

const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

let ball = new Ball(15, 15, 300)
ball.draw(ctx)

let isPaused = true
let k = 0

window.addEventListener('keydown', (e) => {
    if(e.keyCode === 39){
        animate(isPaused)
        if(k === 0){
            isPaused = !isPaused
            k++
        } //수정이 필요한 부분입니다 😂
    }
})

function animate(isPaused){
    if(isPaused){      
        ball.moveRight()
        ball.draw(ctx)
        window.requestAnimationFrame(animate)
    }
  // 여기에 대해 할 말이 많은데,,,
  
  // 1. 먼저 console.log(isPaused)를 
  // if문 안에다가 추가해서
  // console에 확인해보면 true가 아닌 이상한 값들이 출력됨
  // !=isPaused 여서 그런가...?
  
  
  // 2. window.removeAnimationFrame
  // - requestid를 requestAnimationFrame이 반환
  // - 그 점을 이용해 연타됐을 때, id로 frame을 제거 해보려고 했음
  // - 되긴 하는데 연타했을 때, 끊김현상 발생
  // 솔직히 2번과 관련해서 지금 나도 잘 이해안감,,,
}

ball.js

export default class Ball{
    constructor(rad, xpos, ypos){
        this.rad = rad
        this.xpos = xpos
        this.ypos = ypos
        this.speed = 0
        this.accel = 3
    }

    draw(ctx){
        ctx.clearRect(0, 0, 800, 600)
        ctx.beginPath()
        ctx.arc(this.xpos, this.ypos, this.rad, 0, Math.PI * 2)
        ctx.fillStyle = 'steelblue'
        ctx.fill()
    }

    moveRight(){
        if(this.xpos + this.rad >= 800){
            this.xpos = 800 - this.rad
            return
        }
        else{
            this.xpos += this.accel
        }
    }
}

isPaused를 이용...

isPausedk를 사용해
오른쪽 키 연타 시, 공이 가속되는 문제를 방지

👍 결과

live server에서는 안 끊기는데,,, screenToGif가 프레임이 많이 낮네 ㅠ

profile
꽉찬 5년

0개의 댓글