Canvas Draw

// ์บ”๋ฒ„์Šค์— ๊ทธ๋ฆผ๊ทธ๋ฆฌ๊ธฐ 
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle = '#BADA55'; 
ctx.lineJoin = 'round'; // ์„ ์ด ๊บฝ์ด๋Š” ๋ถ€๋ถ„์˜ ์Šคํƒ€์ผ ์ง€์ •
ctx.lineCap = 'round';  // ์„  ๋ ๋ถ€๋ถ„์˜ ์Šคํƒ€์ผ ์ง€์ •
ctx.lineWidth = 100;
// ctx.globalCompositeOperation = 'multiply';

let isDrawing = false; // ๊ทธ๋ฆผ์„ ๊ทธ๋ฆฐํ›„์— ๋งˆ์šฐ์Šค๋ฅผ ๋• ์„๋•Œ ๋ฉˆ์ถฐ์•ผํ•˜๋ฏ€๋กœ 
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;

function draw(e) {
  if (!isDrawing) return; // mouse down ์•„๋‹ˆ๋ฉด ํ•จ์ˆ˜์‹คํ–‰์„ ๋ฉˆ์ถฐ๋ผ 
  ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;// ๋„ํ˜•์˜ ์œค๊ณฝ์„  ์ƒ‰์„ ์„ค์ •
  ctx.beginPath();  // ์บ”๋ฒ„์Šค๋ฅผ ์‹œ์ž‘ํ•  ๋•Œ ์ƒˆ๋กœ์šด path๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ
  // start from
  ctx.moveTo(lastX, lastY);
  // go to
  ctx.lineTo(e.offsetX, e.offsetY);    //e.offsetX, e.offsetY ๋งˆ์šฐ์Šค ์ด๋™์— ๋”ฐ๋ผ EventListener๋ฅผ ๊ฑธ์–ด ๋†“์€ ์ด๋ฒคํŠธ ๊ฐ์ฒด -> ๋งˆ์šฐ์Šค ์œ„์น˜๋ฅผ ๋ฐ˜ํ™˜ ํ•˜๊ณ  draw ํ•จ์ˆ˜์—์„œ ์ด๋ฅผ ์‚ฌ์šฉ
  ctx.stroke(); // ์œค๊ณฝ์„ ์„ ์ด์šฉํ•˜์—ฌ ๋„ํ˜•์„ ๊ทธ๋ฆฌ๋Š” ํ•จ์ˆ˜
  [lastX, lastY] = [e.offsetX, e.offsetY]; 

  hue++;
  if (hue >= 360) {
    hue = 0;
  }
  if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {
    direction = !direction;
  }

  if(direction) {
    ctx.lineWidth++;
  } else {
    ctx.lineWidth--;
  }

}

canvas.addEventListener('mousedown', (e) => {   //์ด๋ฒคํŠธ๋ฆฌ์Šค๋„ˆ๋ฅผ ์ถ”๊ฐ€
  isDrawing = true;
  [lastX, lastY] = [e.offsetX, e.offsetY];
});


canvas.addEventListener('mousemove', draw); // ๋งˆ์šฐ์Šค๊ฐ€ ์›€์ง์ผ๋•Œ draw ํ•จ์ˆ˜ ์‹คํ–‰
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);

canvas.addEventListener("mousedown", (e) => {
    if (e.which === 1) {
      isDrawing = true;
      [lastX, lastY] = [e.offsetX, e.offsetY];
    } else if (e.which === 3) {
// canvas ์ง€์šฐ๋Š” ๋ถ€๋ถ„
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
  });

Last updated