[Javascript] requestAnimationFrame
์ด๊ฑด ์ ๋๋ฉ์ด์ ์ด๋ ๊ทธ๋ํฝ ์ฒ๋ฆฌ ๋ฑ์ ๋งค์ฐ ์ ์ฉํ ๋ธ๋ผ์ฐ์ ๋ด์ฅํจ์๋ค.
window.๏ปฟrequestAnimationFrame(์ฝ๋ฐฑํจ์)
๊ธฐ๋ณธ์ ์ธ ์๋ฆฌ๋ ๊ฐ๋จํ๋ฐ, ์ฝ๋ฐฑ์ ๋ฐ์์ ๊ทธ๋ฅ ๋ธ๋ผ์ฐ์ ๊ฐ ๋ ๋๋ง์ ํ๊ธฐ ์ง์ ์ ์คํ์์ผ์ค ๋ฟ์ด๋ค.
ํญ์ ๋ ๋๋ง ์ ์๋ง ํธ์ถ๋๋ ๋ถํ์ํ ์ฐ์ฐ์ด๋ ํ๋ฐ์ ์์ด ๋ฑ๋ฑ ํ์ด๋ฐ์ ๋ง์ถฐ์ ๋ฐ์ดํฐ๋ฅผ ์ธํ
ํ๊ณ ๋ถ๋๋ฝ๊ฒ ๋ณด์ฌ์ค ์๊ฐ ์๋ค.
์ด๊ฑธ ์ด์ฉํด์ ์บ๋ฒ์ค ๋ ๋๋ง์ ํ๋ค๋ฉด, ์ด๋ฐ์์ผ๋ก ํ ์ ์์ ๊ฒ์ด๋ค.
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
<script>
function drawCircle(color) {
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
context.beginPath();
context.arc(100, 75, 50, 0, 2 * Math.PI);
context.fillStyle = color
context.fill()
context.stroke();
}
let red = '#ff0000'
let blue = '#0000ff'
let color = red;
function animationEvent(timestamp){
if (color === red) {
console.log(1)
color = blue
} else {
console.log(2)
color = red
}
drawCircle(color)
window.requestAnimationFrame(animationEvent);
}
window.requestAnimationFrame(animationEvent);
</script>
</html>
requestAnimationFrame๋ ํ๋์ ์ด๋ฒคํธ๋ง ์คํํ๋ฉด ๊ทธ๋๋ก ๊ทธ๋ง์ด๊ธฐ ๋๋ฌธ์, ์ฌ๊ธฐ์๋ ์ฌ๊ทํธ์ถ๋ก ๊ณ์ํด์ ํธ๋ฆฌ๊ฑฐ๋ฅผ ๊ฑธ๋๋ก ํ๋ค.
๊ทธ๋ผ ์ด๋ ๊ฒ ๊ณ์ ์์ด ๋ฐ๋ ๊ฒ์ด๋ค.
๋ด ๋
นํ ํ๋ก๊ทธ๋จ์ด ๋ ๋๋ง ์๋๋ฅผ ๋ชป๋ฐ๋ผ๊ฐ์ ์ฒ์ฒํ ๋ฐ๋๋ ๊ฒ์ฒ๋ผ ๋ณด์ด๋๋ฐ, ์ค์ ๋ก๋ ๊ต์ฒด์๋๊ฐ ๋๋ฌด ๋นจ๋ผ์ ๋ณด๋ผ์์ผ๋ก ๋ณด์๋ค.
๊ทธ๋ ๋ค.
์ฐธ์กฐ
https://developer.mozilla.org/ko/docs/Web/API/Window/requestAnimationFrame