사소한 개발지식/로드맵(FE)

[로드맵] FrontEnd - JavaScript #2

2023. 2. 2. 19:43
목차
  1. 2. Browser APIs
  2. DOM manipulation
  3. Events API
  4. Fetch API
  5. Canvas API
  6. Fullscreen API
  7. Clipboard API
  8. Geolocation API
728x90
반응형

Fron-end 로드맵 중 Front-end 부분 - 드림코딩

https://www.youtube.com/watch?v=TTLHd3IyErM - 드림코딩 Front-end 로드맵 영상

JavaScript

2. Browser APIs

browser API (or Web API)는 브라우저에게 기본으로 제공되는 API를 말한다. DOM 조작, 네트워크 통신을 요청, 클라이언트 측 저장소를 관리, 장치 미디어 스트림 검색 등을 위한 다양한 API가 있다.

.

DOM manipulation

DOM이란 HTML 및 XML 문서를 위한 프로그래밍 인터페이스로 프로그램이 문서 구조, 스타일, 내용을 변경할 수 있도록 페이지를 나타내며 문서를 노드와 객체로 나타내 프로그래밍 언어가 페이지에 연결할 수 있도록 하는 인터페이스.

/*==== Element 생성 ====*/
const div = document.createElement('div')


/*==== Element 추가 ====*/
const div = document.createElement('div')
const p = document.createElement('p')

p.append('test')	// TEXT 추가
div.append(p)		// p태그(요소) 추가

const div = document.createElement('div')
const p = document.createElement('p')

div.appendChild(p)	// p태그(요소) 추가


/*==== Element 조회 ====*/
const one = document.querySelector('.list')	// class가 list인 Element 중 첫번째 노드
const all = document.querySelecotr('.list')	// class가 list인 Element 노드 전체
const id = document.getElementById('name')	// id가 name인 Element 노드


/*==== Element 수정 ====*/
// '홍길동' 으로 value 속성 추가
document.getElementById('name').setAttribute('value', '홍길동')

// class 에 test 추가
document.getElementById('name').classList.add('test')

// text 값을 가져오거나 text을 수정
element.textContent = 'update'
element.innerHTML = 'update'
 

Introduction to the DOM - Web APIs | MDN

The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. This guide will introduce the DOM, look at how the DOM represents an HTML document in memory and how to use APIs to

developer.mozilla.org

.

Events API

마우스나 키보드를 조작하여 어떠한 기능을 실행하는 것을 이벤트라고 하며 이러한 이벤트를 감지하고 특정 코드를 실행할 수 있도록 하는 API

const btn1 = docu,ent.getElementById('btn1')
const btn2 = docu,ent.getElementById('btn2')
const monitor = document.getElementById('monitor')

btn1.addEventListener('click', clickBtn1)
btn2.addEventListener('click' function () {
	monitor.innerHTML = 'btn2 click!!!'
})

function clickBtn1 () {
	monitor.innerHTML = 'btn1 click!!!'
}

/*
btn1 을 클릭하면 monitor 요소에 'btn1 click!!!' 이 보여진다.
btn2 를 클릭하면 monitor 요소에 'btn2 click!!!' 이 보여진다.
*/
 

이벤트 입문 - Web 개발 학습하기 | MDN

이벤트(event)란 여러분이 프로그래밍하고 있는 시스템에서 일어나는 사건(action) 혹은 발생(occurrence)인데, 이는 여러분이 원한다면 그것들에 어떠한 방식으로 응답할 수 있도록 시스템이 말해주

developer.mozilla.org

.

Fetch API

Fetch API는 브라우저에서 네트워크 요청을 수행하는데 사용된다.

// GET
fetch('https://api.test.com/posts')
  .then(response => response.json())
  .then(json => console.log(json))

// POST
fetch('https://api.test.com/posts', {
    method: 'POST',
    body: JSON.stringify({
      title: 'title',
      body: 'body',
      userId: 1
    }),
    credentials: 'include',
    headers: {
      'Content-type': 'application/json; charset=UTF-8'
    }
  })
  .then(response => response.json())
  .then(json => console.log(json))

// PUT
fetch('https://api.test.com/posts/1', {
    method: 'PUT',
    body: JSON.stringify({
      id: 1,
      title: 'title',
      body: 'body',
      userId: 1
    }),
    credentials: 'include',
    headers: {
      'Content-type': 'application/json; charset=UTF-8'
    }
  })
  .then(response => response.json())
  .then(json => console.log(json))

// DELETE
fetch('https://api.test.com/posts/1', {
  method: 'DELETE'
})
 

Fetch API - Web APIs | MDN

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.

developer.mozilla.org

.

Canvas API

Canvas API는 javascript 및 HTML을 사용하여 그래픽을 그리는 데 사용된다. 사진 조작, 비디오 처리, 데이터 시각화 및 게임 개발과 같은 분야에서 사용된다.

<!DOCTYPE html>
<html>
  <head>Canvas API demo</head>
  <body>
    <canvas id="canvas"> </canvas>
    <script>
      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');

      // draw rectangle
      ctx.fillStyle = 'yellow';
      ctx.fillRect(10, 10, 150, 100);
    
      // draw circle
      var centerX = canvas.width / 2;
      var centerY = 65;
      var radius = 50;

      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
      ctx.fillStyle = 'red';
      ctx.fill();

      // draw triangle
      ctx.beginPath();
      ctx.moveTo(350, 10);
      ctx.lineTo(350, 200);
      ctx.lineTo(500, 200);
      ctx.closePath();
      ctx.fillStyle = 'blue';
      ctx.fill();
    </script>
  </body>
</html>

 

 

Canvas API - Web APIs | MDN

The Canvas API provides a means for drawing graphics via JavaScript and the HTML <canvas> element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.

developer.mozilla.org

.

Fullscreen API

Fullscreen API는 특정 DOM 요소를 전체 화면으로 전환할 수 있는 API

async function goFullScreen() {
  document.getElementById('fullscreen')
    .requestFullscreen()
    .then((res) => {
       console.log('Went full screen');
    })
    .catch((err) => {
       console.log('Fullscreen error: ', err);
    });
}

async function handleExitFullScreen() {
  document.exitFullscreen()
    .then((res) => {
       console.log('Exit full screen success');
    })
    .catch((err) => {
       console.log('Fullscreen error: ', err);
    });
}
 

Fullscreen API - Web APIs | MDN

The Fullscreen API adds methods to present a specific Element (and its descendants) in fullscreen mode, and to exit fullscreen mode once it is no longer needed. This makes it possible to present desired content—such as an online game—using the user's e

developer.mozilla.org

.

Clipboard API

Clipboard API는 Clipboard에 쓰기/읽기 작업을 할 수 있도록 하는 API

// Write text data to the clipboard
async function copyText(){
  try{
    await navigator.clipboard.writeText(document.getElementById('val').value)
    alert('Copied to clipboard');
  }
  catch(err){
    console.log('Copied to clipboard err: ',err);
  }
}

// Read text data from the clipboard
async function pasteText(){
  try{
    const readText = await navigator.clipboard.readText()
    document.querySelector('#pasted-value').innerText += readText
  }
  catch(err){
    console.log('paste text error: ',err)
  }    
}

 // Write data (eg: text/plain, image/png etc) to the clipboard
 async function copyData(){
    try{
      const data = await fetch('https://i.imgur.com/RGuxleZ.png');
      const blob = await data.blob();
      await navigator.clipboard.write([
        new ClipboardItem({[blob.type]: blob})
      ]);
      alert('Image copied.');
    }
    catch(err){
      console.log('Error occured when copying image data: ',err)
    }
 }

// Read data (eg: text/plain, image/png etc) from the clipboard
function pasteData(){
  // Requesting explicit permission of the user
  navigator.permissions.query({name: 'clipboard-read'}).then(async result => {
    // If the permission is already granted or the user will be prompted to allow it
    if (result.state == 'granted' || result.state == 'prompt') {
      try {
        const clipboardItems = await navigator.clipboard.read();
        for (const clipboardItem of clipboardItems) {
          for (const type of clipboardItem.types) {
            if(type === 'image/png'){
              const blob = await clipboardItem.getType(type);
              document.getElementById('pasted-img').src= URL.createObjectURL(blob)
            }
          }
        }
      } catch (err) {
         console.error(err.name, err.message);
      }
    }
  });
}
 

Clipboard API - Web APIs | MDN

The Clipboard API provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard.

developer.mozilla.org

.

Geolocation API

Geolocation API는 사용자가 Web Application에 자신의 위치를 알릴 수 있다. 위치 검색 전 개인정보보호를 위해 명시적으로 허가를 요청한다.

<html>

<body>
    <button id="location">location</button>
    <button id="track">track</button>
    <div id="status">Status</div>
</body>

<script
    const status = document.querySelector("#status");

    function getCurrentLocation() {

      if (navigator.geolocation) {
        status.textContent = "Locating…";
        navigator.geolocation.getCurrentPosition(success, error);
      } else {
        status.textContent = "Geolocation is not supported by your browser";
      }
    }

    function trackUserLocation() {
      if (navigator.geolocation) {
        status.textContent = "Locating…";
        navigator.geolocation.watchPosition(success, error);
      } else {
        status.textContent = "Geolocation is not supported by your browser";
      }
    }

    function success(position) {
      const latitude = position.coords.latitude;
      const longitude = position.coords.longitude;

      status.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
    }

    function error() {
      status.textContent = "Unable to retrieve your location";
    }

    document.querySelector("#location").addEventListener("click", getCurrentLocation);
    document.querySelector("#track").addEventListener("click", trackUserLocation);
</script>

</html>

 

 

Geolocation API - Web APIs | MDN

The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

developer.mozilla.org

.

참조
https://javascript.plainenglish.io/6-browser-apis-you-need-to-know-as-a-front-end-developer-76752633280b
728x90
반응형
저작자표시 (새창열림)
  1. 2. Browser APIs
  2. DOM manipulation
  3. Events API
  4. Fetch API
  5. Canvas API
  6. Fullscreen API
  7. Clipboard API
  8. Geolocation API
'사소한 개발지식/로드맵(FE)' 카테고리의 다른 글
  • [로드맵] FrontEnd - CSS 심화 #2
  • [로드맵] FrontEnd - CSS 심화 #1
  • [로드맵] FrontEnd - JavaScript #1
  • [로드맵] FrontEnd - CSS #4
KimBY
KimBY
웹개발과 관련된 개발지식 모음
B.Y Kim의 개발노트웹개발과 관련된 개발지식 모음
KimBY
B.Y Kim의 개발노트
KimBY
전체
오늘
어제
  • 분류 전체보기 (99)
    • 사소한 개발지식 (49)
      • PHP (2)
      • JavaScript (15)
      • NodeJS (0)
      • JAVA (2)
      • 잡?지식 (4)
      • 로드맵(FE) (22)
      • React (4)
    • 개발노트 (6)
      • 포트폴리오사이트 (6)
    • 프로그래머스 (33)
      • Level1(JS) (0)
      • Level2(JS) (33)
    • 백준알고리즘 (11)
      • 단계별로 풀어보기3(for문) (11)
    • 잡담 (0)

인기 글

최근 글

최근 댓글

태그

  • CSS
  • 백준알고리즘
  • javascript
  • 프로그래머스
  • 로드맵
  • react
  • Level2
  • frontend
  • 단계별로풀어보기
  • FE로드맵
hELLO · Designed By 정상우.
KimBY
[로드맵] FrontEnd - JavaScript #2
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.