Today I Learned #22

YoungToMaturityยท2021๋…„ 1์›” 30์ผ
1

Javascript

๋ชฉ๋ก ๋ณด๊ธฐ
13/17
post-thumbnail

paintJS ๊ทธ๋ฆผ ๊ทธ๋ฆฌ๊ธฐ ๊ธฐ๋Šฅ ๊ตฌํ˜„

ํ˜„์žฌ๊นŒ์ง€ ์ง„ํ–‰๋œ paintJS๋Š” canvas๊ฐ€ ๊ตฌํ˜„๋˜์–ด์žˆ์œผ๋ฉฐ, ๊ฐ ์ƒ‰์ƒ์— ํ•ด๋‹นํ•˜๋Š” button, ๋ถ“์˜ ๋‘๊ป˜๋ฅผ ์ •ํ•˜๋Š” range๋ฅผ ๊ตฌํ˜„ํ•˜์˜€์ง€๋งŒ, canvas ์ž์ฒด์˜ ๊ทธ๋ฆผ์„ ๊ทธ๋ฆฌ๋Š” ๊ธฐ๋Šฅ๊ณผ, ํ•ด๋‹น button๊ณผ range๋ฅผ ํ†ตํ•œ ๊ฐ’์ด ์ „๋‹ฌ๋˜๋Š” ๊ธฐ๋Šฅ์€ ๊ตฌํ˜„๋˜์ง€ ์•Š์•˜๋‹ค. ๋”ฐ๋ผ์„œ canvas์— ๊ทธ๋ฆผ์„ ๊ทธ๋ฆฌ๋Š” ๊ธฐ๋Šฅ์„ ๋จผ์ € ๊ตฌํ˜„ํ•ด๋ณด๋„๋ก ํ•˜์˜€๋‹ค.

์„ ์–ธ ๋ฐ ์„ค์ •

MDN context ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ, canvas์˜ context๋ฅผ ์„ค์ •ํ•ด์ฃผ์—ˆ๋‹ค.

const ctx = canvas.getContext("2d");
ctx.strokeStyle = "#2c2c2c";
ctx.lineWidth = 2.5;
canvas.width = 500 ;
canvas.height = 500;

๋˜ํ•œ strokeStyle์„ ํ†ตํ•ด ์ƒ‰์ƒ์„ ์ •ํ•ด์ฃผ๊ณ , ํŽœ์˜ ๋‘๊ป˜๋ฅผ ์˜๋ฏธํ•˜๋Š”lineWidth์˜ ์ดˆ๊ธฐ๊ฐ’์€ 2.5๋กœ ์„ ์–ธํ•˜๊ณ , html <canvas>์˜ ํฌ๊ธฐ์™€ ๊ฐ™๋„๋ก canvas.width์™€ canvas.height์˜ ๊ฐ’์„ ๊ฐ๊ฐ 500์œผ๋กœ ์ง€์ •ํ•ด์ฃผ์—ˆ๋‹ค.

onMouseMove

startPainting๊ณผ stopPaintingํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด let์œผ๋กœ ์„ ์–ธํ•ด์ฃผ์—ˆ๋˜ painting์˜ ๊ฐ’์„ ์‹œ์ž‘ํ• ๋•Œ true๋กœ, ๋๋‚ ๋•Œ false๋กœ ๋ฐ”๋€Œ๋„๋ก ์„ ์–ธํ•ด์ฃผ๊ณ , ํ•ด๋‹น painting์˜ ๊ฐ’์— ๋”ฐ๋ผ ํ•จ์ˆ˜๊ฐ€ ์ง„ํ–‰๋˜๋„๋ก ํ•˜์˜€๋‹ค.

function onMouseMove(event) {
    const x = event.offsetX;
    const y = event.offsetY;
    if(!painting) {
        ctx.beginPath();
        ctx.moveTo(x,y);
    } else {
        ctx.lineTo(x,y);
        ctx.stroke();
    }
}

๋จผ์ €, "mousemove"๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ, painting์˜ ๊ฐ’์ด false์ธ ๊ฒฝ์šฐ, context์˜ path๋ฅผ ํ•ด๋‹น ๋งˆ์šฐ์Šค๊ฐ€ ์œ„์น˜ํ•œ x,y์—์„œ ์‹œ์ž‘ํ•˜๋„๋ก ์„ ์–ธํ•˜๊ฒŒ ํ–ˆ๋‹ค. ๊ทธ๋Ÿฌ๋Š” ๊ณผ์ •์—์„œ, ์ฆ‰ ์‚ฌ์šฉ์ž์˜ ๋งˆ์šฐ์Šค๊ฐ€ canvas์œ„๋ฅผ ์›€์ง์ด๋‹ค๊ฐ€ mousedown(ํด๋ฆญ)์ด ๋ฐœ์ƒํ–ˆ์„ ๋•Œ, painting์€ true๋กœ ๋ฐ”๋€Œ๊ฒŒ ๋˜๊ณ , ๊ทธ ๋ฐ”๋กœ ์ง์ „์˜ x,y์—์„œ ์ƒ์„ฑ๋œ beginPath()์—์„œ path๊ฐ€ ์‹œ์ž‘๋˜๊ณ , lineTo(x,y)๋ฅผ ํ†ตํ•ด์„œ ์ด๋™๋œ x,y๊นŒ์ง€ path๊ฐ€ ์ด์–ด์ง€๊ณ , stroke() ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๋งค๋ฒˆ "mousemove"๊ฐ€ ๋ฐœ์ƒํ•  ๋•Œ๋งˆ๋‹ค path๊ฐ€ strokeStyle์˜ ์ƒ‰์ƒ๊ณผ lineWidth ๊ฐ’์˜ ๋‘๊ป˜๋กœ ์ƒ‰์น ๋œ๋‹ค.


์‹คํ–‰ ๊ฒฐ๊ณผ

profile
iOS Developer

0๊ฐœ์˜ ๋Œ“๊ธ€