학교수업/웹프로그래밍

Graphics

Ynghan 2023. 6. 16. 02:10

The Browser Object Model(BOM)

The Browser Object Model(BOM)

브라우저 객체 모델(BOM)을 사용하면 자바스크립트가 브라우저와 "대화"할 수 있습니다.
즉, 브라우져 자체를 의미하여 브라우져의 정보를 얻을 수 있고 정보를 변경할 수도 있다.
일종의 브라우저에 대한 Builtin Function을 제공

The Window Object

window 개체는 브라우저의 창을 나타냅니다.
전역 변수와 브라우져에 관련된 다양한 기능을 제공
모든 전역 자바스크립트 객체는 자동으로 window 객체의 멤버가 됩니다.
- 글로발 객체, 함수, 변수 등의 멤버가 됩니다.
- 전역 함수는 window 객체의 메서드입니다.
    - 그러니까 객체의 내부가 아닌 전역 범위에서의 this는 Window가 됨

document 객체도 window 객체의 속성입니다:
window.document.getElementById("header");
    - document.getElementById("header")와 동일합니다;
window는 생략 가능

Window Size

window.innerHeight - 브라우저 창의 내부 높이(픽셀 단위)
window.innerWidth - 브라우저 창의 내부 너비(픽셀 단위)

window.location property

window.location 객체를 사용하여 현재 페이지 주소(URL)를 가져오고 를 가져와 브라우저를 새 페이지로 리디렉션하는 데 사용할 수 있습니다.
window.location 객체는 window 접두사 없이 작성할 수 있습니다.
window.location.href는 현재 페이지의 href(URL)를 반환합니다.
    window.location.hostname은 웹 호스트의 도메인 이름을 반환합니다.
    window.location.pathname은 현재 페이지의 경로와 파일명을 반환합니다.
    window.location.protocol은 사용된 웹 프로토콜을 반환합니다(http: 또는 https:).
    window.location.assign()은 새 문서를 로드합니다.

window.history

window.history 객체에는 브라우저 기록이 포함됩니다.
window.history 객체는 window 접두사 없이 작성할 수 있습니다.
사용자의 개인 정보를 보호하기 위해 자바스크립트가 이 객체에 액세스할 수 있는 방법에는 제한이 있습니다.
    몇 가지 메서드
    history.back() - 브라우저에서 뒤로 클릭하는 것과 동일합니다.
    history.forward() - 브라우저에서 앞으로 클릭하는 것과 동일합니다.

window.navigator

window.navigator 개체에는 방문자의 브라우저에 대한 정보가 포함되어 있습니다.

window.navigator 객체는 window 접두사 없이 작성할 수 있습니다.


Canvas Graphics

HTML로 그래픽을 실행하는 방법은 크게 다음 2가지가 있다.
    - Canvas에 Javascript비트맵 스타일로 그림을 그린다.
    - SVG로 그리는 방법도 있으며, 이는 각 그림이 요소들로 그려진다.

Canvas Examples

캔버스는 HTML 페이지의 직사각형 영역입니다.
기본적으로 캔버스에는 테두리도 없고 콘텐츠도 없습니다.
자바스크립트 추가하기
    - 직사각형 캔버스 영역을 만든 후에는 그림을 그리기 위해 JavaScript를 추가해야 합니다.
<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>

</body>
</html>
canvas 요소를 getElementById로 DOM으로 가져옵니다.
getContext("2d")를 사용하여 2차원으로 지정하여 변수 ctx에 저장합니다.
ctx를 0,0으로 옮기고 200,100으로 선을 잡아줍니다.
stroke 메소드로 두 점을 이어 그려줍니다.

 

beginPath()

캔버스에 두 개의 경로(녹색과 보라색)를 그립니다:
<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();              
ctx.lineWidth = "5";
ctx.strokeStyle = "green";  // Green path
ctx.moveTo(0, 75);
ctx.lineTo(250, 75);
ctx.stroke();  // Draw it

ctx.beginPath();
ctx.strokeStyle = "purple";  // Purple path
ctx.moveTo(50, 0);
ctx.lineTo(150, 130);            
ctx.stroke();  // Draw it
</script>

</body>
</html>
canvas 요소를 받아옵니다.(getElementById)
getContext("2d")로 2차원으로 지정합니다.
beginPath() 사용 → 경로를 그리기 위해 초기화하는 역할 : 새로운 선을 그릴때 이전 선을 무시하고 새롭게 시작 가능.
굵기 지정, 색상 지정, 출발점 지정, 이동한 점 지정, 그리기 메소드 사용
beginPath() 사용
색상 지정, 출발점 지정, 이동한 점 지정, 그리기 메소드 사용

 

원 그리기

캔버스에 원을 그리려면 다음 메서드를 사용합니다:
beginPath() - 경로를 시작합니다.
arc(x,y,r, startangle, endangle) - 호/커브를 만듭니다.
    arc()로 원을 만들려면 다음과 같이 하세요: startangle을 0으로 설정하고 endangle을 2*Math.PI로 설정합니다.
    x 및 y 매개 변수는 원의 중심을 정의합니다.
    r 매개 변수는 원의 반지름을 정의합니다.
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
</script>

삼각형 그리기

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>

<script>
 
function fill() {
  var canvas = document.getElementById('myCanvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(75, 50);
    ctx.lineTo(100, 75);
    ctx.lineTo(100, 25);
    ctx.fill();
  }
}
fill()
</script> 
</body>
</html>
fill 함수
    canvas 요소를 가져옴.
    getContext("2d") 해줌.
    beginPath()로 초기화 시켜줌.
    1) 이동 2) 선그리기 3) 선그리기 4) 선으로 둘러쌓인 삼각형 색 채우기

 

텍스트 그리기

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
</script>
canvas 요소 가져오기
getContext("2d")
font : 폰트 지정.
fillText( 텍스트 내용, x, y)

 

선형 그라데이션 그리기

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
</script>
createLinearGradient(x, y, x1, y1)
addColorStop(offset, color);
    offset : 0과 1 사이의 값으로, 그라디어느에서의 색상의 위치를 지정합니다.
    color : 그라디언트에서 해당 위치에 있는 색상을 지정합니다.

 

원형 그라데이션 그리기

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
</script>
createRadialGradient( x, y, r, x1, y1, r1 ) - 방사형/원형 그라데이션 생성

 

이미지 그리기

<!DOCTYPE html>
<html>
<body>

<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">

<p>Canvas to fill:</p>
<canvas id="myCanvas" width="250" height="300"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>

<p><button onclick="myCanvas()">Try it</button></p>

<script>
function myCanvas() {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var img = document.getElementById("scream");
  ctx.drawImage(img,10,100);
}
</script>

</body>
</html>
drawImage(img 요소, x, y)

JavaScript Timing Events

 

타이밍 이벤트

window 객체를 사용하면 지정된 시간 간격으로 코드를 실행할 수 있습니다.
이러한 시간 간격을 타이밍 이벤트라고 합니다.
자바스크립트에서 사용할 수 있는 두 가지 주요 메서드는 다음과 같습니다:
    setTimeout(function, milliseconds)
        지정된 시간(밀리초) 동안 기다린 후 함수를 실행합니다.
    setInterval(function, milliseconds)
        setTimeout()과 동일하지만 함수 실행을 계속 반복합니다.

 

setTimeout() 메소드

window.setTimeout() 메소드는 window 접두사 없이 작성할 수 있습니다.
1초 = 1000밀리초
<button onclick="setTimeout(myFunction, 3000)">Try it</button>

<script>
function myFunction() {
  alert('Hello');
}
</script>
3초 기다렸다가 myFunction 실행

 

setInterval() 메서드

setInterval() 메서드는 지정된 시간 간격마다 지정된 함수를 반복합니다.
setInterval(myTimer, 1000);

function myTimer() {
  const d = new Date();
  document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
myTimer 메소드를 1초 간격으로 반복 실행
실행을 중지하는 방법은 무엇인가요?
    - clearInterval() 메서드는 setInterval() 메서드에 지정된 함수의 실행을 중지합니다.
<p id="demo"></p>

<button onclick="clearInterval(myVar)">Stop time</button>

<script>
let myVar = setInterval(myTimer, 1000);
function myTimer() {
  const d = new Date();
  document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
myVar 변수로 1초 간격으로 myTimer 메소드 반복 실행해주고 
clearInterval(myVar) : myVar 메소드를 인자로 받아서 실행을 중단시킨다.

SVG Graphics

SVG는 벡터 기반 그래픽을 XML 형식으로 정의합니다.
SVG는 Canvas가 아닌 HTML의 요소로 그림을 그린다.
요소란 의미는 <h1> <button> 과 동일한 종류라는 의미!

 

SVG란 무엇인가요?

SVG는 Scalable Vector Graphics(확장 가능한 벡터 그래픽)의 약자입니다.
SVG는 웹용 그래픽을 정의하는 데 사용됩니다.
SVG는 W3C 권장 사항입니다.

 

HTML <svg> 요소

HTML <svg> 요소는 SVG 그래픽을 위한 컨테이너입니다.
SVG에는 경로, 상자, 원, 텍스트 및 그래픽 이미지를 그리는 여러 가지 방법이 있습니다.

 

SVG Circle

<!DOCTYPE html>
<html>
<body>

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40"
  stroke="green" stroke-width="4" fill="yellow" />
Sorry, your browser does not support inline SVG.
</svg>
 
</body>
</html>
svg 요소와 그 안에 circle 요소의 속성들을 이용해 그림을 그립니다.

 

Canvas와 비교

svg는 html로 작성하고 canvas는 자바스크립트로만 작성된다.

 

SVG Rectangle

<svg width="400" height="100">
  <rect width="400" height="100" 
  style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" />
Sorry, your browser does not support inline SVG.
</svg>
rect 요소와 그에 속성을 사용.

 

SVG Rounded Rectangle

<svg width="400" height="180">
  <rect x="50" y="20" rx="20" ry="20" width="150" height="150"
  style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />
Sorry, your browser does not support inline SVG.
</svg>
rect 요소에 style 속성을 사용하여 1) 안쪽 색상, 2) 선 색상, 3) 선 굵기, 4) 안쪽 투명도 를 지정하였다.

'학교수업 > 웹프로그래밍' 카테고리의 다른 글

HTTP  (0) 2023.06.16
Bootstrap: CSS Framework  (0) 2023.06.16
[0323~0328] 웹프  (0) 2023.03.23
[웹프] 0316~0321  (0) 2023.03.16
[웹프] 0314  (0) 2023.03.14