본문 바로가기

TIL

[TIL-110] 노마드코더 그림판(JS) 클론코딩 #1.0~#2.3

#1 셋업 + 스타일

레포지토리 만들기

  • README 파일 추가
  • .gitignore는 node로 추가
  • 내 pc에 복제 : git clone https://github.com/JUNSEULGI/paintjs (레포지토리 주소)
    • 꼭 명령어로 안 해도 됨.

 

프로젝트 셋업

  • index.html에 app.js(<body>에 <script>로)와 styles.css(<head>에 <link>로) 연결.
  • 깃 커밋하기
    • git add .
    • git commit -m "Initial Commit"
    • [에러] 깃헙 계정이 연결되어있지 않은 듯... 
더보기
더보기

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: empty ident name (for <junseulgi@DESKTOP-JKRIJ1Q.localdomain>) not allowed 

 

 

CSS 셋업

  • reset css 임포트
  • body : 배경색, 폰트 지정. flex 설정.
  • <canvas> 태그 생성
    • 자바스립트에 이용할 id="jsCanvas"
    • CSS에 이용할 class="canvas"
    • .canvas 스타일
      • box-shadow : 그림자 효과
        box-shadow: 0 4px 6px rgba(50,50,93,0.11), 0 1px 3px rgba(0,0,0,0.08);
  • 색상 컨트롤 div 생성
    • div.controls > div.controls__colors > div.controls__color*9
    • div.controls__color 9개를 하나하나 지목해서 css 넣기보단 그냥 html에서 인라인으로 스타일 넣음.
    • cursor : 커서 모양
      cursor: pointer;
  • button 생성 : fill, save
    • div.controls__btns>button#jsMode+button#jsSave
    • button#jsMode : "Fill"로 입력해둠. 디폴트를 painting으로 해서 클릭하면 fill로 바뀌고, 다시 클릭하면 painting이 되게 함.
    • all: unset;은 버튼의 기본 서식을 모두 없애줌. 모양새부터 커서까지 다 새로 만들어줘야 함.
    • text-transform: uppercase;는 입력한 알파벳을 대문자로 바꿔줌.
    • transform: scale(0.98);은 버튼 클릭하면 살짝 작아졌다가 커지는 효과.
      .controls__btns button:active {
        transform: scale(0.98);
      }​
  • range input 생성
    • <input type="range" id="jsRange" min="0.1" max="5.0" value="2.5" step="0.1"/>
    • min, max 속성으로 최소값과 최대값을 정하고, value로 기본값을 줄 수 있다.
    • step 속성으로 조절 단위를 정할 수 있다.

 

 

#2 자바스크립트

캔버스 이벤트

  • "mousemove" 이벤트 : 캔버스 위에 마우스 커서가 움직이는 것 감지
    • offset : 이벤트가 담고 있는 정보 중에서 offsetX, offsetY 필요함. 캔버스 내의 좌표.
      • clientX, clientY : 윈도우 전체 범위 내에서 마우스의 위치값. 캔버스가 스크린 사이즈라면 offsetX와 clientX는 동일할 것.
  • let painting = false;
    • "mousedown" 이벤트 : 캔버스가 클릭되는 것 감지
      • 클릭되면 painting 변수의 값을 true로 바꿈.
    • "mouseup" 이벤트 : 캔버스에 클릭한 상태가 해제되는 것 감지 
      • 클릭한 마우스를 놓을 때 painting은 다시 false가 됨. 이렇게 껐다 켰다함.
    • "mouseleave" 이벤트 : 마우스가 캔버스를 벗어나는 것 감지
      • 마우스가 캔버스를 밖으로 나가도 painting은 false가 됨.
    • stopPainting()
      • painting=false는 반복되기 때문에 따로 함수를 만듦.

 

2D Context

  • context
    • <canvas> 태그는 context를 갖는다는 특징 있음.
    • context는 요소 안에서 픽셀에 접근할 수 있는 방법.
    • 사용법 : context 변수 만듦.
      • const ctx = canvas.getContext("2d");
        
        // 선 그리기
        ctx.lineWidth = 10;
        
        // 사각형 그리기
        ctx.strokeRect(75, 140, 150, 110);
        
        // 색 칠해진 사각형 그리기
        ctx.fillRect(130, 190, 40, 60);
        
        // 지붕 그리기
        ctx.beginPath();
        ctx.moveTo(50, 140);	// context 옮기기
        ctx.lineTo(150, 60);	// 다른 곳에 라인 그리기
        ctx.lineTo(250, 140);
        ctx.closePath();
        ctx.stroke();
      • 참고) https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
    • [2.2] canvas를 픽셀을 다룰 수 있는 요소로 만들기 위해, css 사이즈뿐 아니라 pixel manipulating 사이즈를 줘야 함.
      • canvas.width = 700;
      • canvas.height = 700;
  • context 기본값 설정
    ctx.strokeStyle = "#2c2c2c";
    ctx.lineWidth = 2.5;​
    • strokeStyle : 색상이나 스타일을 선에 사용할 수 있음.
      • cf) fillStyle : 색상이나 스타일을 shape 안에 사용할 수 있음.
    • lineWidth : range input으로 조절할 선 두께.
  • path : 기본적인 선
    • beginPath() : 선을 시작함.
    • moveTo() : 선을 움직임.
    • closePath() : 선을 닫음.
    • lineTo() : 현재 sub-path의 마지막 점을 특정 좌표와 직선으로 연결.
    • fill() : 현재의 fill style로 현재 sub-path를 채움.
    • stroke() : 현재의 stroke style로 현재 sub-path에 획을 그음.
  • 마우스가 캔버스 위를 움직일 때(mousemove)
    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();
      }
    }​
    • (painting === false) : path를 만들고, 움직이는 마우스의 새로운 좌표로 path를 옮김. 그럼 마우스가 움직일 때마다 매번 작은 선(path)이 만들어짐. 하지만 아직 path가 사용되진 않은 상태.
    • (painting === true) : 마우스가 클릭해서(mousedown) true가 되면, path의 이전 위치에서 움직인 위치(좌표)로 연결하는 선을 긋고 색을 칠함. 이로써 path가 사용된 것.

 

색깔 바꾸기

  • controls__colors에 자바스크립트용 jsColor 클래스 추가.
  • jsColor 태그들을 배열로 불러오기
    • const colors = document.getElementsByClassName("jsColor"); 결과는 HTMLCollection이라는 객체로 나온다.
    • Array.from(객체) : 객체로부터 배열을 만들어주는 메소드.
    • Array.from(colors).forEach(color => color.addEventListener("click", handleColorClick));
  • handleColorClick() 함수
    function handleColorClick(event) {
      const color = event.target.style.backgroundColor;
      ctx.strokeStyle = color;
    }​
    • event 인자를 사용해 event.target.style에 들어가보면 타겟 요소의 backgroundColor 값 가져올 수 있음.
    • context color 변경.