ํ์ฌ๊น์ง ์งํ๋ 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์ผ๋ก ์ง์ ํด์ฃผ์๋ค.
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
๊ฐ์ ๋๊ป๋ก ์์น ๋๋ค.