๊ณต๋ถ€ ๊ธฐ๋ก โœ๏ธ/Javascript

JS-Do it! JS - #10์ผ (14,15)

๋ฒ„๋‘˜ 2023. 4. 1. 10:25

14. ์บ”๋ฒ„์Šค๋กœ ๋„ํ˜•,ํ…์ŠคํŠธ,์ด๋ฏธ์ง€ ๊ทธ๋ฆฌ๊ธฐ

 

๊ฒฝ๋กœ๊ทธ๋ฆฌ๊ธฐ์˜ ์‹œ์ž‘๊ณผ ๋์„ ๋‚˜ํƒ€๋‚ด๋Š” beginPath() , closePath()

๊ฒฝ๋กœ๋ฅผ ๋งŒ๋“ค๊ฒ ๋‹ค ์•Œ๋ฆฌ๋Š” beginPath()

๊ฒฝ๋กœ๊ทธ๋ฆฌ๊ธฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ ค๋ฉด ๋ฐ˜๋“œ์‹œ ์‚ฌ์šฉ, 

ํ•˜์ง€๋งŒ ์‹œ์ž‘์œ„์น˜=๋์œ„์น˜ ๊ฐ™๋‹ค๋ฉด, closePath()๋Š” ์ƒ๋žต ๊ฐ€๋Šฅ ,๊ทธ ์™ธ์—๋Š” ๋ถ™์—ฌ์•ผ ํ•œ๋‹ค.

 

 


15. ์บ”๋ฒ„์Šค๋กœ ๊ทธ๋ž˜ํ”ฝ ์š”์†Œ ๋‹ค๋ฃจ๊ธฐ

 

๋‚˜๋งŒ์˜ ๋“œ๋กœ์ž‰ ์•ฑ ๋งŒ๋“ค๊ธฐ 

const canvas = document.querySelector("#canvas");
const toolbar = document.querySelector("#toolbar");

// ์บ”๋ฒ„์Šค ๋„ˆ๋น„์™€ ๋†’์ด. toolbar.offsetHeight๋Š” ํˆด๋ฐ”์˜ ๋†’์ด
canvas.width = window.innerWidth;
canvas.height = window.innerHeight - toolbar.offsetHeight;

// ์บ”๋ฒ„์Šค ์œ„์น˜๋ฅผ ๊ณ ๋ คํ•ด ์ขŒํ‘œ ๊ณ„์‚ฐํ•˜๊ธฐ ์œ„ํ•ด
const canvasOffsetX = canvas.offsetLeft;   // ์™ผ์ชฝ์—์„œ ์–ผ๋งˆ๋‚˜ ๋–จ์–ด์กŒ๋‚˜
const canvasOffsetY = canvas.offsetTop;    // ์œ„์—์„œ ์–ผ๋งˆ๋‚˜ ๋–จ์–ด์กŒ๋‚˜

const ctx = canvas.getContext("2d");

let isDrawing = false;     // ๋“œ๋กœ์ž‰ ์ƒํƒœ์ธ์ง€ ํ™•์ธ
let startX;       // ๊ทธ๋ฆฌ๊ธฐ ์‹œ์ž‘ํ•˜๋Š” ์ขŒํ‘œ, x
let startY;       // ๊ทธ๋ฆฌ๊ธฐ ์‹œ์ž‘ํ•˜๋Š” ์ขŒํ‘œ, y
let lineWidth = 2;    // ์„  ๊ตต๊ธฐ ๊ธฐ๋ณธ ๊ฐ’

// ์„  ์ƒ‰๊ณผ ์„  ๊ตต๊ธฐ๋ฅผ ์„ ํƒํ–ˆ์„ ๋•Œ
toolbar.addEventListener("change", e => {
  if (e.target.id === "stroke") {
    ctx.strokeStyle = e.target.value;
  }
  if (e.target.id === "lWidth") {
    lineWidth = e.target.value;
  }
});

// '์ง€์šฐ๊ธฐ' ๋ฒ„ํŠผ ๋ˆ„๋ฅด๋ฉด ์บ”๋ฒ„์Šค ์ง€์šฐ๊ธฐ
toolbar.addEventListener("click", e => {
  if (e.target.id === "reset") {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  }
});

canvas.addEventListener("mousedown" , e => {
  isDrawing = true;
  startX = e.clientX;
  startY = e.clientY;
});

canvas.addEventListener("mousemove", (e) => {
  if (!isDrawing) return;
  ctx.lineWidth = lineWidth;
  ctx.lineCap = "round";
  ctx.lineTo(e.clientX, e.clientY - canvasOffsetY);
  ctx.stroke();
});

canvas.addEventListener("mouseup", () => {
  isDrawing = false;
  ctx.beginPath();
});

 

GOOD ๊ธ€์”จ ๋ฐฐ๊ฒฝ์ด๋ฏธ์ง€๋กœ ์ฑ„์šฐ๊ธฐ

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.font = "bold 300px sans-serif";
ctx.fillText("GOOD", 100, 320);

ctx.globalCompositeOperation="source-in";

let img=new Image();
img.onload=()=>{
    ctx.drawImage(img,0,0,canvas.width,canvas.height);
}
img.src="images/text-bg.jpg";

'๊ณต๋ถ€ ๊ธฐ๋ก โœ๏ธ > Javascript' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

JS-Do it! JS - #12์ผ (17,18)  (0) 2023.04.03
JS-Do it! JS - #11์ผ (16)  (0) 2023.04.01
JS-Do it! JS - #9์ผ (11,12,13)  (0) 2023.03.30
JS-Do it! JS - #8์ผ (09,10)  (0) 2023.03.23
JS-Do it! JS - #7์ผ์ฐจ (08)  (0) 2023.03.23