์ปดํจํฐ ๊ทธ๋ํฝ์ค์์ ์คํ๋ผ์ดํธ(์์ด: sprite)๋ ์์ ์์ ์์ 2์ฐจ์ ๋นํธ๋งต์ด๋ ์ ๋๋ฉ์ด์ ์ ํฉ์ฑํ๋ ๊ธฐ์ ์ด๋ค. ์ด๊ธฐ์๋ 2D ๋น๋์ค ๊ฒ์์์ ๋น๋์ค ์์๊ณผ ๋ถ๋ฆฌ๋ ๋ณ๋์ ๊ทธ๋ํฝ์ค ๊ฐ์ฒด๋ฅผ ์๋ฏธํ์ง๋ง, ์ค๋๋ ์๋ ๋ค์ํ ์ธต์ ์ด๋ฏธ์ง, ํ ์คํธ ๋ฑ์ ๊ฐ๊ฐ์ ์ฐ์ ์์๋ฅผ ๋๊ณ ํฉ์ฑํ๋ ๊ธฐ์ ์ ํตํ์ด ์ผ์ปซ๋๋ค.
From. ์ํค๋ฐฑ๊ณผ - ์คํ๋ผ์ดํธ (์ปดํจํฐ ๊ทธ๋ํฝ์ค)
const $canvas = document.querySelector('#canvas1');
const _ctx = $canvas.getContext('2d');
$canvas.width = 500;
$canvas.height = 500;
<canvas>
์ attr์ ์ ์ธํด๋ ๋๋ค./* drawImage
context.drawImage(
[์ฝ์
ํ ์ด๋ฏธ์ง],
[sprite ์์ ์์น x],
[sprite ์์ ์์น y],
[sprite ๋๋น],
[sprite ๋์ด],
[์ถ๋ ฅ ์ด๋ฏธ์ง ์์ ์์น X],
[์ถ๋ ฅ ์ด๋ฏธ์ง ์์ ์์น Y],
[์ถ๋ ฅ ์ด๋ฏธ์ง ๋๋น],
[์ถ๋ ฅ ์ด๋ฏธ์ง ๋์ด],
)
*/
๋ฉ์๋
ํด๋์ค ํธ์ถ ๋ฐ ๊ธฐ๋ณธ animate ์ค์
const mandrake = new Animation($canvas.width, $canvas.height);
function animate() {
// _ctx.clearRect([์บ๋ฒ์ค ์์ ์์น X], [์บ๋ฒ์ค ๋ ์์น Y], [์บ๋ฒ์ค ๋๋น], [์บ๋ฒ์ค ๋์ด]);
_ctx.clearRect(0, 0, $canvas.width, $canvas.height);
mandrake.draw(_ctx);
mandrake.update();
requestAnimationFrame(animate);
}
animate();
์ฝ๋ฐฑ ํจ์์ mandrake.setAnimation([์์ ํ๋ ์], [๋ ํ๋ ์]) ์ ์ธ
radio
๋ฅผ button
์ผ๋ก ๋ณ๊ฒฝdata-*
์์ฑ์ผ๋ก [์์ ํ๋ ์]๊ณผ [๋ ํ๋ ์] ์ค์ dataset
์ผ๋ก ๋ฐ์์จ ๊ฐ์ ๋ฐ์ดํฐ ํ์ ๋ฌธ์์ด์ด๋ฏ๋ก ์ซ์ํ์ผ๋ก ๋ณ๊ฒฝํ๋ค.<!-- index.html -->
<button type="button" data-min="0" data-max="75">Grow</button>
<button type="button" data-min="76" data-max="112">Wink</button>
...
// page_sprite.js
const groupControl = document.querySelector('.group-control');
groupControl.addEventListener('click', function (e) {
const $target = e.target;
const _min = $target.dataset.min;
const _max = $target.dataset.max;
mandrake.setAnimation(Number(_min), Number(_max));
});
'2D'๋ ์๋ฌ๊ฐ ๋๊ณ '2d'๋ ์ ์์ผ๋ก ๋์ํ๋ค.
// ์๋ฌ
const $canvas = document.querySelector('#sprite_canvas');
const _ctx = $canvas.getContext('2D');
// ์ ์
const $canvas = document.querySelector('#sprite_canvas');
const _ctx = $canvas.getContext('2d');
canvas ํฌ๊ธฐ ๊ฐ์ ์ซ์ํ์ผ๋ก ์ค์ ํ๋ค.
// ์๋ฌ
$canvas.width = '500px';
$canvas.height = '500px';
// ์ ์
$canvas.width = 500;
$canvas.height = 500;
์ถ์ฒ
Franks Laboratory - JavaScript Sprite Animation
MDN - getContext