paintJS์์ ์ง๊ธ๊น์ง ๋ง๋ค์ด ์จ 9๊ฐ์ div์ ์ด์ฉํ์ฌ, ๊ฐ ๋ฒํผ์ ํด๋ฆญํ์์ ๋ ํด๋น ๋ฒํผ์ ์์์ผ๋ก ํ์ ์์์ด ๋ณ๊ฒฝ๋๋๋ก ํ๋ ๊ธฐ๋ฅ์ ๊ตฌํ
๊ธฐ์กด์ html ํ์ผ์๋ <div class="controls__color" style="background-color: #2c2c2c"></div>
์ ๊ฐ์ div
๊ฐ ๊ฐ๊ฐ ๋ค๋ฅธ background-color
๋ฅผ ๊ฐ๊ณ 9๊ฐ๊ฐ ์์ฑ๋์ด์๋ค. ๋ํ, css์์ cursor: pointer
๋ก ์ค์ ๋์ด์๊ธฐ ๋๋ฌธ์ ์ฌ์ฉ์๊ฐ ํด๋ฆญ์ด ๊ฐ๋ฅํ ์์์์ ํ์ธํ ์ ์๊ฒ ํ์๋ค. ์ดํ js ํ์ผ์์ const colors = document.getElementsByClassName("jsColor");
๋ฅผ ํตํด colors
๋ก ํด๋น ๊ฐ์ฒด๋ค์ ์ ์ธํ์ฌ ์์ ๋กญ๊ฒ ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋๋ก ํ์๋ค.
Array.from MDN ๋ฌธ์๋ฅผ ์ฐธ๊ณ ํ๋ฉด, ๋ค์๊ณผ ๊ฐ์ ๋ด์ฉ์ ํ์ธํ ์ ์๋ค.
๋ค์๊ณผ ๊ฐ์ ๊ฒฝ์ฐ์ Array.from()์ผ๋ก์Array๋ฅผ ๋ง๋ค ์ ์์ต๋๋ค.
- ์ ์ฌ ๋ฐฐ์ด ๊ฐ์ฒด (length ์์ฑ๊ณผ ์ธ๋ฑ์ฑ๋ ์์๋ฅผ ๊ฐ์ง ๊ฐ์ฒด)
- ์ํ ๊ฐ๋ฅํ ๊ฐ์ฒด (Map, Set ๋ฑ๊ฐ์ฒด์ ์์๋ฅผ ์ป์ ์ ์๋ ๊ฐ์ฒด)
document.getElementsByClassName()
์ ํตํด ์ป์ด์จ ๊ฒฐ๊ณผ๊ฐ์ length
์์ฑ๊ณผ ์ธ๋ฑ์ฑ ๋ ์์๋ฅผ ๊ฐ์ง ๊ฐ์ฒด์ด๊ธฐ ๋๋ฌธ์, Array.from()
์ ์ฌ์ฉํ ์ ์๊ณ , ํด๋น ๋ฉ์๋๋ฅผ ํตํด return ๋ Array๋ฅผ forEach()
๋ฅผ ํตํด Array์ ๊ฐ๊ฐ์ ์์์ ๋ํด ์ธ์๋ก์ ์ ๋ฌ๋๋ ์ฝ๋ฐฑ ํจ์๋ฅผ ์ ์ฉํ์๋ค.
Array.from(colors).forEach(color =>
color.addEventListener("click", handleColorClick));
๋ค์๊ณผ ๊ฐ์ด ์ฝ๋๋ฅผ ์์ฑํ์๊ณ , colors
์ ์ํ ์์๋ค์ Array๋ก ๋ฐ๊พผ ํ์, ๊ฐ๊ฐ์ ์์์ธ color
์ "click"
์ด๋ฒคํธ ๋ฐ์์ handleColorClick
ํจ์๊ฐ ๋ฐ์ํ๋๋ก ํ๋ event listener๋ฅผ ์ถ๊ฐํด์ฃผ์๋ค.
๊ฐ๊ฐ์ color
์ ๋ํ์ฌ "click"
์ด๋ฒคํธ๊ฐ ๋ฐ์ํ ๊ฒฝ์ฐ ํด๋น ์์์ผ๋ก ํ์ ์์์ ๋ฐ๊พธ๊ฒ ํ๋ ํจ์ handleColorClick
์ ๋ด์ฉ์ ๊ฐ๋จํ๋ค.
function handleColorClick(event) {
const color = event.target.style.backgroundColor;
ctx.strokeStyle = color;
}
ํด๋น div
์ backgroundColor
์์ฑ์ color
๋ผ๋ ์ด๋ฆ์ ์ง์ญ๋ณ์๋ก ์ ์ธํด์ฃผ๊ณ , CanvasRenderingContext2D
์ ์์ฑ์ ํด๋นํ๋ ctx
์ strokeStyle
์ ์์ ์ ์ธํ color
๋ก ์ง์ ํด์ฃผ๋ฉด ์ ์์ ์ผ๋ก ์์์ด ๋ฐ๋์ ํ์ธํ ์ ์๋ค.