Vanilla JS 30

30 Day Vanilla JS Coding Challenge Study - 3주차

  • Ajax Type Ahead with fetch()
  • Array Cardio Day 2
  • Let’s build something fun with HTML5 Canvas

6. Ajax Type Ahead with fetch()

영상: https://youtu.be/y4gZMJKAeWs

미리 준비된 JSON Data를 Fetch API를 사용하여 받아온 후 정규표현식을 통해 조작한다.

1
2
3
fetch(endpoint)
.then(blob => blob.json())
.then(data => cities.push(...data));
  • body.json()를 사용하여 JSON을 파싱하는데 JSON.parse()와 다른 부분이 흥미롭다
    body.json()의 경우 비동기이며 Promise 객체를 반환한다.

참고자료: body.json() vs JSON.parse()

1
2
3
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
  • 3자리 단위로 콤마를 찍어주는 정규표현식
1
2
3
4
5
6
7
8
// Case 1
const regex = new RegExp(wordToMatch, 'gi');
return place.city.match(regex) || place.state.match(regex)

// Case 2
const regex = new RegExp(this.value, 'gi');
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
  • 정규표현식 메서드를 사용하기 위한 방법

7. Array Cardio Day 2

영상: https://youtu.be/QNmRfyNg1lw

JavaScript Array 강화 훈련2

이전에 나왔던 4강의 JavaScript Array Cardio Practice - Day 1과 별 다를게 없었다.

강의 속 사용된 Array Method

  • Array.prototype.some
  • Array.prototype.every
  • Array.prototype.find
  • Array.prototype.findIndex

8. Let’s build something fun with HTML5 Canvas

영상: https://youtu.be/8ZGAzJ0drl0

HTML5 Canvas를 활용한 그림판

1
<canvas id="draw" width="800" height="800"></canvas>
  • 캔버스 DOM 요소 생성
1
2
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
  • 캔버스 생성시 렌더링 타입을 getContext()를 통해 초기화해줘야한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 윤곽선 색상
ctx.strokeStyle = '#BADA55';
// 모서리 스타일
ctx.lineJoin = 'round';
// 선의 끝점 스타일
ctx.lineCap = 'round';
ctx.lineWidth = 100;
// 도형이 겹쳐질때의 방식
ctx.globalCompositeOperation = 'multiply';
// 도형을 그릴때의 시작 경로
ctx.beginPath();
// 지정된 좌표로 이동
ctx.moveTo(lastX, lastY);
// 지정된 위치까지 선을 그린다
ctx.lineTo(e.offsetX, e.offsetY);
// 현재 or 지정된 경로로 윤곽선을 그린다.
ctx.stroke();

전체적인 로직은 마우스 이벤트를 감지한 후 캔버스 객체를 활용하여 그림을 그리는 방식이다.

Share Comments