๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
JavaScript/Vanilla JS

[๋ฐ”๋‹๋ผJS๋กœ ๊ทธ๋ฆผํŒ ๋งŒ๋“ค๊ธฐ] Changing Color

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 4. 27.
๋ฐ˜์‘ํ˜•

[์ถœ์ฒ˜-์œ ํŠœ๋ธŒ ๋…ธ๋งˆ๋“œ ์ฝ”๋” Nomad Coders]

https://youtu.be/cq-l2zPUVoU

 

Recap ํ›„์— ์šฐ๋ฆฌ๊ฐ€ ํ•  ์ผ์€ ์ƒ‰์ƒ์„ ๋ฐ”๊พธ๋Š” ๊ฒƒ์ด๋‹ค.

 

 

index.html

<div class="controls__colors" id="jsColors">
    <div class="controls__color jsColor" style="background-color: black;"></div>
    <div class="controls__color jsColor" style="background-color: white"></div>
    <div class="controls__color jsColor" style="background-color: #ff3b3c"></div>
    <div class="controls__color jsColor" style="background-color: #ff9500"></div>
    <div class="controls__color jsColor" style="background-color: #ffcc00"></div>
    <div class="controls__color jsColor" style="background-color: #4cd963"></div>
    <div class="controls__color jsColor" style="background-color: #5ac8fa"></div>
    <div class="controls__color jsColor" style="background-color: #0579ff"></div>
    <div class="controls__color jsColor" style="background-color: #5856d6"></div>
</div>

 

 

 

app.js

const colors = document.getElementsByClassName("jsColor");
console.log(Array.from(colors));

๊นœ๋นกํ•˜๊ณ  closePath()๋ฅผ ์•ˆ์ง€์›€....

 

 

 

function handleColorClick(event) {
    console.log(event.target.style);
}
Array.from(colors).forEach(color => 
    color.addEventListener("click", handleColorClick)
);

์ƒ‰์„ ํด๋ฆญํ• ๋•Œ๋งˆ๋‹ค array๋ฅผ ๊ฐ€์ง„๋‹ค.

 

 

 

์ข€ ๋” ๋‹ค๋“ฌ์–ด๋ณด์ž.

function handleColorClick(event) {
    const color = event.target.style.backgroundColor;
    console.log(color);
}

 

 

 

๊ทธ๋ฆฌ๊ณ  ์ง€๊ธˆ์€ strokeStyle์ด ๊ฒ€์ •์ƒ‰์œผ๋กœ ์ง€์ •๋˜์–ด์žˆ์ง€๋งŒ

strokeStyle์„ overrideํ•˜๋ฉด handleColorClick ํ•จ์ˆ˜์—์„œ๋Š” strokeStyle์ด target์— ์žˆ๋Š” ์ƒ‰์ƒ์ด ๋˜๋Š” ๊ฒƒ์ด๋‹ค.

function handleColorClick(event) {
    const color = event.target.style.backgroundColor;
    ctx.strokeStyle = color;
}

์šฐ๋ฆฌ๊ฐ€ ํ•œ๊ฑด ctx.strokeStyle์„ ๋ฐ”๊พผ ๊ฒƒ ๋ฐ–์— ์—†๋‹ค.

๊ทธ๋ฆฌ๊ณ  color์„ target์œผ๋กœ๋ถ€ํ„ฐ ๋ฐ›์•„์„œ ๋„ฃ์€ ๊ฒƒ ๋ฟ์ด๋‹ค.

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€