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

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

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

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

https://youtu.be/LAG1ERXR2xQ

 

์ด์ „ ๊ฐ•์˜์—์„œ ํ”„๋กœ๊ทธ๋žจ์ด ์ž‘๋™์ด ์•ˆ๋œ๊ฑด canvas์— ์‚ฌ์ด์ฆˆ๋ฅผ ์•ˆ์ค˜์„œ ๊ทธ๋Ÿฐ ๊ฒƒ ๊ฐ™๋‹ค.

canvas element๋Š” ๋‘ ๊ฐœ์˜ ์‚ฌ์ด์ฆˆ๋ฅผ ๊ฐ€์ ธ์•ผ ํ•œ๋‹ค.

CSS ์‚ฌ์ด์ฆˆ์™€ ์›น๋ธŒ๋ผ์šฐ์ € ์ƒ์˜ ์‚ฌ์ด์ฆˆ.

์ด element์— width, height๋ฅผ ์ง€์ •ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

canvas.width = 700;
canvas.height = 700;
const canvas = document.getElementById("jsCanvas");
const ctx = canvas.getContext("2d");

canvas.width = 700;
canvas.height = 700;

ctx.strokeStyle = "#2c2c2c";
ctx.lineWidth = 2.5;

let painting = false;

function stopPainting() {
    painting = false;
}

function startPainting() {
    painting = true;
}

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();
    }
}

function onMouseDown(event) {
    painting = true;
}

if(canvas) {
    canvas.addEventListener("mousemove", onMouseMove);
    canvas.addEventListener("mousedown", startPainting);
    canvas.addEventListener("mouseup", stopPainting);
    canvas.addEventListener("mouseleave", stopPainting);
}

wow!!!!!!!!!!! ์ž‘๋™ํ•œ๋‹ค!!!!!!!!!!!

์‹ค์ œ pixel ์‚ฌ์ด์ฆˆ๋ฅผ ์•ˆ์ค˜์„œ ์ž‘๋™์„ ์•ˆํ•œ๊ฑฐ์˜€์Œ...

canvas๋ฅผ ๋ฒ—์–ด๋‚˜๋ฉด painting์ด ์ค‘์ง€๋จ.

 

 

 

ctx.strokeStyle = "#2c2c2c";

ctx.strokeStyle์€ ์šฐ๋ฆฌ๊ฐ€ ๊ทธ๋ฆด ์„ ๋“ค์ด ๋ชจ๋‘ #2c2c2c(๊ฒ€์ •์ƒ‰)์„ ๊ฐ–๋Š”๋‹ค๊ณ  ๋งํ•˜๊ณ  ์žˆ์Œ.

์ด context ์•ˆ์— ์žˆ๋Š” ์„ ๋“ค์€ ๋ชจ๋‘ #2c2c2c ์ƒ‰์„ ๊ฐ–๋Š”๋‹ค๋Š” ๋œป์ž„.

 

ctx.lineWidth = 2.5;

lineWidth๋Š” ๊ทธ ์„ ์˜ ๋„ˆ๋น„๊ฐ€ 2.5px๋ผ๋Š” ๊ฒƒ์ด๋‹ค.

 

 

 

path๋Š” ์„ ์ด๋‹ค.

path๋ฅผ ๋งŒ๋“ค๋ฉด ๋งˆ์šฐ์Šค์˜ x, y ์ขŒํ‘œ๋กœ path๋ฅผ ์˜ฎ๊ธด๋‹ค.

path์˜ ์‹œ์ž‘์ ์€ ๋งˆ์šฐ์Šค๊ฐ€ ์žˆ๋Š” ๊ณณ์ด๋‹ค.

 

(๊ทธ ๋‹ค์Œ ์„ค๋ช…์€ ๋‹ˆ๊ผฌ์Œค์˜ ๊ฐ•์˜๋ฅผ ๋ณด๋ฉด์„œ ๋จธ๋ฆฌ์†์œผ๋กœ ์ดํ•ดํ•˜๋Š”๊ฒŒ ๋น ๋ฅด๋‹ค)

 

 

 

์ž ๊น! ) ๋งŒ์ผ closePath()๋ฅผ ์“ฐ๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ผ์ด ๋ฐœ์ƒํ•œ๋‹ค.

ctx.closePath();
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();
        ctx.closePath();
    }
}

path๊ฐ€ ๋๋‚˜๋ฒ„๋ฆฌ๊ธฐ๋•Œ๋ฌธ์— ์ €๋ ‡๊ฒŒ ๊ทธ๋ ค์ง..

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€