-
자바스크립트 기본 문법HTML 2023. 10. 26. 17:34
기본 용어
표현식: 값을 만들어 내는 간단한 코드
문장: 프로그래밍 언어에 실행할 수 있는 코드의 최소 단위
문장 마지막에 세미콜론(;) 또는 줄 바꿈을 넣어 종결을 나타냄
273; 10 + 20 + 30 * 2; var name = '윤' + '인' + '성'; alert('Hello JavaScript');
문장 예
273 10 + 20 + 30 * 2 'JavaScript'
표현식 예
키워드
자바스크립트를 처음 만들 때 정해진 특별한 의미가 부여된 단어
식별자
자바스크립트에서 변수나 함수 등에 이름을 붙일 때 사용하는 단어
키워드 사용 x
특수 문자는 _와 $만 허용
숫자로 시작하면 x
공백 입력 x
구분 단독으로 사용 다른 식별자와 함께 사용 식별자 뒤에 괄호 x 변수 속성 식별자 뒤에 괄호 o 함수 메서드 주석
방법 형태 한 행 주석 처리 // 주석문 여러 행 주석 처리 /*
주석문
주석문
*/자바스크립트 출력
자바스크립트의 가장 기본적인 출력 방법은 alert() 함수를 이용해 웹 브라우저에 경고 창 띄우는 것
<!DOCTYPE html> <html> <head> <title>JavaScript Basic</title> <script> alert('Hello JavaScript .. !'); </script> </head> <body> </body> </html>
함수 내부에 입력한 문자열 확인
크롬 - F12
입력하면 바로 결과 나옴 문자열 따옴표로 묶고 싶은 경우 이스케이프 문자 설명 예 \t 수평 탭 > '한빛\t아카데미'
"한빛 아카데미"\n 행 바꿈 > '한빛\n아카데미'
"한빛
아카데미"\\ 역 슬래시 > '\\\\'
\\\' 작은따옴표 > '\'\'\''
" ' ' ' "\" 큰따옴표 >"\"\"\""
" " " " "불
불은 참과 거짓을 표현할 때 사용하는 자료
콘솔 탭에 수식 입력하면 true 또는 false로 출력됨 > 불
두 대상을 비교할 수 있는 비교 연산자
숫자, 문자열도 비교 가능
문자열은 국어사전의 앞쪽에 위치할수록 값이 작음
연산자 설명 예 ! 논리 부정(참이면 거짓, 거짓이면 참) && 논리곱(둘 다 참이어야 함) | | 논리합(둘 중 하나만 참이어도 참) 변수
값을 저장할 때 사용하는 식별자
변수 사용
1. 변수 선언
2. 변수 초기화
변수 만드는 것을 '변수를 선언한다'고 표현, let 키워드 뒤에 식별자를 입력하는 방법으로 선언
> let pi; // 변수 선언 undefined > pi = 3.14159265; // 값 할당 undefined
변수를 선언한 후 처음 값을 할당하는 것을 변수를 초기화한다고 표현
> let pi = 3.14159265; undefined
변수에 값이 저장되면 변수를 사용해 저장된 값을 활용 가능
> let pi = 3.14159265; undefined > alert(pi); undefined
변수 사용
<script> // 변수를 선언 및 초기화 let radius = 10; let pi = 3.14159265; //출력 alert(2 * radius * pi); </script>
조건문과 반복문
조건문
참과 거짓 판별
<script> // 조건문 if (273 < 52) { // 표현식 "273 < 52"가 참일 때 실행 alert('273 < 52 => true'); } // 프로그램 종료 alert('프로그램 종료'); </script>
현재 시간 구하기
<script> // Data 객체를 선언 let date = new Date(); // 요소 추출 let year = date.getFullYear(); let month = date.getMonth() + 1; // 프로그래밍에서는 일반적으로 1월을 0으로 표시해 익숙한 월 표현을 위해 1씩 더함 let day = date.getDay(); let hours = date.getHours(); let minutes = date.getMinutes(); let seconds = date.getSeconds(); </script>
오전과 오후 구분
<script> // 변수 선언 let date = new Date(); let hours = date.getHours(); // 조건문 if (hours < 12) { // 표현식 "hours < 12"가 참일 때 실행 alert('오전') } if (12 <= hours) { // 표현식 "12 <= hours"가 참일 때 실행 alert('오후') } </script>
if else 조건문
<script> // 변수 선언 let date = new Date(); let hours = date.getHours(); // 조건문 if (hours < 12) { // 표현식 "hours < 12"가 참일 때 실행 alert('오전') } else { // 표현식 "12 <= hours"가 참일 때 실행 alert('오후') } </script>
중첩 조건문과 if else if 조건문
중첩 조건문으로 하루 일정 표현
<script> // Date 객체 선언: 현재 시간 측정 let date = new Date(); let hours = date.getHours(); // 조건문 if (hours < 5) { alert('잠자기'); } else { if (hours < 7) { alert('준비'); } else { if (hours < 9) { alert('출근'); } else { if (hours < 12) { alert('빈둥'); } else { if (hours < 14) { alert('식사'); } else { // 여러 가지 업무를 수행 } } } } } </script>
if else if 조건문으로 하루 일정 표현
<script> // Date 객체 선언: 현재 시간 측정 let date = new Date(); let hours = date.getHours(); // 조건문 if (hours < 5) { alert('잠자기'); } else if (hours < 7) { alert('준비'); } else if (hours < 9) { alert('출근'); } else if (hours < 12) { alert('빈둥'); } else if (hours < 14) { alert('식사'); } else { // 여러 가지 업무를 수행 } </script>
논리 연산자와 조건문
<script> // Date 객체 선언: 현재 시간 측정 let date = new Date(); let month = date.getMonth() + 1; // 조건문 if (3 <= month && month <= 5) { alert('봄'); } else if (6 <= month && month <= 8) { alert('여름'); } else if (9 <= month && month <= 11) { alert('가을'); } else { alert('겨울'); } </script>
<script> // Date 객체 선언: 현재 시간 측정 let score score = 100 // 조건문 if (score == 100 or score >= 96) { alert("GRADE='A+'"); } else if (score >= 93) { alert("GRADE='A'"); } else if (score >= 90) { alert("GRADE='A-'"); } else if (score >= 87) { alert("GRADE='B+'"); } else if (score >= 83) { alert("GRADE='B'"); } else if (score >= 80) { alert("GRADE='B-'"); } else { alert('NO'); } </script>
score = 100 / score = 90 score = 82 / score = 50 반복문
<script> for (let i = 0; i < 10; i++) { alert('출력'); } </script>
확인 10번 누르면 경고창 닫힘 배열: 변수 여러 개를 한꺼번에 다룰 수 있는 자료형
요소 - 배열 내부에 입력된 자료 하나하나
배열 내부에 다양한 자료형 입력 가능
배열 전체를 출력하면 요소가 순서대로 표시
<script> // 변수 선언 let array = ['가', '나', '다', '라']; // 배열 요소 변경 array[0] = '윤'; // 요소 출력 alert(array[0]); alert(array[1]); alert(array[2]); alert(array[3]); alert(array[4]); </script>
배열 요소의 개수
// 변수 선언 let array = ['가', '나', '다', '라']; // 요소 출력 alert(array.length);
while 반복문
가장 기본적인 반복문
if 조건문과 달리 불 표현식이 참이면 중괄호 안 문장 계속 실행
// 반복 수행, i가 배열 원소 개수인 3보다 작을 때 반복 while (true) { alert('무한 반복'); }
<script> // 변수 선언 let i = 0; let array = ['가', '나', '다']; // 반복 수행, i가 배열 원소 개수인 3보다 작을 때 반복 while (i < array.length) { // 출력 alert(i + '번째 출력: ' + array[i]); // 탈출을 위해 변수를 더함 i++; } </script>
for 반복문
for 반복문은 원하는 횟수만큼 반복하고 싶을 때 사용
<script> // 변수 선언 let array = ['가', '나', '다']; // 반복 수행 for (let i = 0; i < 3; i++) { // 출력 alert(i + '번째 출력: ' + array[i]); } </script>
반복문 조건을 외부 요인으로 변경
<script> // 변수 선언 let start = new Date().getTime(); let count = 0; // 반복 수행 while (start + 1000 > new Date().getTime()) { count++; } // 출력 alert(count + '만큼 반복') </script>
for 반복문을 이용한 0부터 1000까지의 합 계산
<script> // 변수 선언 let output = 0; // 반복 수행 for (let i = 0; i <= 100; i++) { output += i; } // 출력 alert(output); </script>
함수
코드의 집합
선언과 호출
방법 표현 익명 함수 function () { } 선언적 함수 function 함수() {
}익명 함수 선언
<script> // 함수 선언 let 함수 = function () { alert('함수_01'); alert('함수_02'); }; // 출력 alert(typeof (함수) + ' : ' + 함수); </script>
선언적 함수 선언
<script> // 함수 선언 function 함수() { alert('함수_01'); alert('함수_02'); }; // 출력 alert(typeof (함수) + ' : ' + 함수); </script>
만들어진 함수는 alert() 함수를 사용했던 것처럼 함수 이름 뒤에 괄호를 사용해 실행 가능
> '함수를 호출한다'고 표현
실행 우선순위
함수도 변수이므로 가장 마지막에 입력된 값이 저장됨
<script> // 함수 선언 함수 = function () { alert('함수_A'); }; 함수 = function () { alert('함수_B'); }; // 함수 호출 함수(); </script>
선언적 함수와 익명 함수를 함께 사용할 때는 실행 순서가 다름
> 자바스크립트는 모든 코드를 읽기 전에 선언적 함수를 먼저 읽음
> 선언적 함수가 익명 함수 뒤에 있어도 나중에 읽은 익명 함수 실행
<script> // 함수 선언 var 함수 = function() { alert('함수_A');}; function 함수 () {alert('함수_B');}; // 함수 호출 함수(); </script>
매개변수와 반환 값
function 함수 이름(매개변수, 매개변수, 매개변수) { // 함수 코드 // 함수 코드 // 함수 코드 return 반환 값; }
이런 형태로 작성
모든 함수에 매개변수와 반환 값을 사용해야 하는 것은 x, 필요할 때만 선택적으로 사용> 매개변수와 반환 값이 있는 함수
<script> // 함수 선언 function f(x) { return x * x; } // 함수 호출 alert(f(3)); </script>
콜백 함수
매개변수로 전달되는 함수
<script> function callTenTimes(callback) { for (let i = 0; i < 10; i++) { callback(); // 매개변수로 전달된 함수 호출 } } let fun = function () { alert('함수 호출'); }; // 함수 호출 callTenTimes(fun); </script> <script> function callTenTimes(callback) { for (let i = 0; i < 10; i++) { callback(); } } // 함수 호출 callTenTimes(function () { alert('함수 호출'); }); </script>
연습 예제
<script> function ShowAsk(question, yes, no) { if (confirm(question) ) {yes(); } else {no() ; } } function CallbackYes() { alert('동의하셨습니다'); } function CallbackNo() { alert('거절하셨습니다'); } ShowAsk('동의하시겠습니까?', CallbackYes, CallbackNo); </script>
확인 눌렀을 때 / 취소 눌렀을 때 <script> function ShowAsk(question, yes, no) { if (confirm(question)) yes() else if (confirm(question)) no() else Giveup(); } function CallbackYes() { alert('동의하셨습니다'); } function CallbackNo() { alert('거절하셨습니다'); } function Giveup() { alert('기권하셨습니다'); } ShowAsk('동의하시겠습니까?', CallbackYes, CallbackNo); </script>
확인 / 취소 - 확인 / 취소 - 취소 연습 문제
// if 조건문을 논리 연산자를 사용해 하나의 if 조건문으로 작성 // if (x > 10) { // if (x < 20) { // alert(x); // } // } if (x > 10 && x < 20) { alert(x); }
// 다음 for 반복문을 while 반복문으로 변경 // for (let i = 1; i <= 10; i++) { // if (i % 5 == 0) { // alert(i); // } // } let i = 1; while (i <= 10) { if (i % 5 == 0) { alert(i); } i++; }
// 다음 while 반복문을 for 반복문으로 변경 // let i = 10; // while(i >= 0) { // alert(i); // i -= 3; // } for (let i = 10; i >= 0; i -= 3;) { alert(i); }
경고창 줄 바꿈
<script> // 변수 선언 let output = '';; output = '첫 번째 줄'; output += '\n'; output += '두 번째 줄';; // 출력 alert(output); </script>
계산
<script> // 변수 선언 let input = parseFloat(prompt('cm 단위를 입력하세요.', '입력')); let inch = input / 2.54; let feet = inch / 12; // 출력 alert(input + '은' + inch + '인치,' + feet + '피트입니다.'); </script>
입력에 10 입력 후 확인
결과 예제 ) 사각형의 넓이 출력
<script> // 변수 선언 let input1 = parseFloat(prompt('밑변 길이를 입력하세요', '입력')); let input2 = parseFloat(prompt('높이를 입력하세요', '입력')); let quad = input1 * input2 // 출력 alert('밑변 길이가 ' + input1 + ', 높이가 ' + input2 + '인 사각형의 넓이는 ' + quad + '입니다.'); </script>
예제 ) 출력 연습
<script> // Date 객체 선언 let date = new Date(); //요소 추출 let year = date.getFullYear(); let month = date.getMonth() + 1; let day = date.getDate(); let hours = date.getHours(); let minutes = date.getMinutes(); let seconds = date.getSeconds(); // 출력 alert(year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds ); </script>
예제 ) 6이 나올 경우의 수
<script> for (let i = 1; i < 7; i += 1){ for (let j = 1; j < 7; j += 1){ if (i + j == 6) { alert(i + '와' + j +'이다.'); } } } </script>
객체
객체는 자료형 여러 개를 한꺼번에 저장
배열과 비슷한 듯하지만 배열은 인덱스를 기반으로 자료 저장, 객체는 키를 기반으로 자료를 저장
객체 개요
<script> // 배열을 선언 let array = ['사과', '바나나', '망고', '딸기']; </script>
(a) 배열 선언
array[0] → '사과' array[1] → '망고'
(b) 배열 이름 뒤에 인덱스를 입력해 배열 요소 접근
<script> // 객체를 선언 let product = { 제품명: '7D 건조 망고', 유형: '당절임', 성분: '망고, 설탕, 메타중아황산나트륨, 치자황색소', 원산지: '필리핀' }; </script>
객체 뒤에 대괄호를 사용해 키를 입력하면 객체 속성에 접근할 수 있음
product['제품명'] → '7D 건조 망고' product['유형'] → '당절임'
객체 뒤에 '.'을 입력하는 방법으로도 객체 속성에 접근할 수 있음, 이 방법을 더 많이 사용
product.제품명 → '7D 건조 망고' product.유형 → '당절임'
식별자로 사용할 수 없는 키
<script> // 객체를 선언 let object = { 'with space': 273, 'with ~!Q#$%^&*()_+': 52 }; // 출력 alert(object['with space']) alert(object['with ~!Q#$%^&*()_+']); </script>
공백이나 특수문자가 섞인 문자를 키로 사용할 때는 반드시 대괄호로 감싸야 객체 요소에 접근 가능
for in 반복문이나 for of 반복문을 사용하면 객체 요소를 하나씩 살펴볼 수 있음
<script> for (let 키 in 객체) { 문장 } </script>
<script> // 객체를 선언 let product = { 제품명: '7D 건조 망고', 유형: '당절임', 성분: '망고, 설탕, 메타중아황산나트륨, 치자황색소', 원산지: '필리핀' }; // 출력 for (let i in product) { alert(i + ':' + product[i]); } </script>
위와 같은 코드를 실행하면 객체 요소가 하나씩 차례로 출력됨
속성과 메서드
배열에 있는 값 하나하나 > 요소
객체에 있는 값 하나하나 > 속성
자바스크립트에서는 요소와 속성이 같다
객체 속성에도 배열 요소처럼 다양한 자료형을 입력할 수 있음
// 객체를 선언 let object = { number: 273, string: 'rintiantta', boolean: true, array: [52, 273, 103, 32], method: function() { } };
객체 속성 중 자료형이 함수인 속성을 특별히 메서드라고 함
<script> // 객체를 선언 let person = { name: '윤인성', eat: function (food) { alert(food + '을/를 먹습니다.'); } }; // 메서드 호출 person.eat('밥') </script>
위 코드에서 person 객체에는 name 속성과 eat 속성이 있음, 그 중 eat 속성의 자료형이 함수이므로 eat() 메서드라고 함
객체에 있는 속성을 메서드에서 사용하고 싶을 때는 자신이 가진 속성임을 분명하게 표시해야 함
이때 this 키워드 사용
<script> // 객체를 선언 let person = { name: '윤인성', eat: function (food) { alert(this.name + '이 ' + food + '을/를 먹습니다.'); } }; // 메서드 호출 person.eat('밥') </script>
위 코드는 객체 생성 후 해당 객체의 속성을 메서드에서 사용하는 것을 모두 보여 줌
ex) eat() 메서드와 name 속성은 person 객체 내부에 있으므로 this 키워드 사용
C++, 자바, C# 등 프로그래밍 언어에서는 this 키워드를 생략할 수 있으나 자바스크립트에서는 this 키워드를 사용하지 않으면 오류 발생
반드시 this 키워드 사용
연습 문제 예제
<script> /* 연습 문제 18 네 자리 정수를 입력받아 천, 백, 십, 일의 자리로 분리해 출력 */ let input = prompt("입력해 주세요", "입력"); let int1 = parseInt(input / 1000); let int2 = parseInt(input%1000 / 100); let int3 = parseInt(input%100 / 10); let int4 = parseInt(input % 10); alert ('천의 자리는: ' + int1 + ', 백의 자리는: ' + int2 + ', 십의 자리는: ' + int3 + ', 일의 자리는: ' + int4) </script>
<script> /* 연습 문제 19 태어난 연도 입력받아 그 해의 띠를 출력하기 */ let input = prompt("태어난 연도 입력", "입력"); let year = { 0 : '원숭이띠', 1 : '닭띠', 2 : '개띠', 3 : '돼지띠', 4 : '쥐띠', 5 : '소띠', 6 : '범띠', 7 : '토끼띠', 8 : '용띠', 9 : '뱀띠', 10 : '말띠', 11 : '양띠' }; let val = parseInt(input % 12); alert (input + '년생은 ' + year[val] +'입니다.') </script>
<script> /* 연습 문제 20 반복문을 사용해 트리 모양 패턴 출력하기 */ let star = ''; for (let i = 1; i <= 10; i += 1) { for (let j=1; j <= i; j += 1) { star += '*'; } star += '\n'; } alert(star) </script>
<script> /* 연습 문제 21 매개변수로 n을 입력받아 n! 반환하는 함수 만들기 */ let n = parseInt(prompt('숫자 입력', '입력')); function f(x) { if (x <= 1) { return x } return x * f(x-1); } alert('n = ' + n + ', n! = ' + f(n)) </script>
<script> /* 연습 문제 22 속성이 가지는 대상을 자바스크립트 객체로 만들기 */ let object = { 이름: 'C# 프로그래밍(2판)', 초판발행: '2021년 1월 5일', 지은이: '윤인성', 펴낸이: '전태호', 펴낸곳: '한빛아카데미(주)', 책임편집: '김성무', 기획: '김성무', 편집: '정서린', 디자인: '최연희, 이아란' }; </script>
캔버스
• 캔버스는 요소로 생성
• 캔버스는 HTML 페이지 상에서 사각형태의 영역
• 실제 그림은 자바스크립트를 통하여 코드로 그려야 함
• 컨텍스트(context) 객체: 자바스크립트에서 물감과 붓의 역할을 함
let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d");
예제 1
<body> <canvas id="myCanvas" width="200" height="100" style="border: 1px dotted red"></canvas> <script> let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); context.fillStyle = "#00FF00"; context.fillRect(0, 0, 100, 50); </script> </body>
직선 그리기 예제 2
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> <script> let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); context.beginPath(); context.moveTo(0, 0); context.lineTo(100, 100); context.lineTo(150, 50); context.lineTo(200, 100); context.stroke(); </script> </body> </html>
사각형 예제 3
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> <script> let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); context.beginPath(); context.rect(10, 10, 100, 100); context.fillStyle = "yellow"; context.fill(); </script> </body> </html>
사각형 예제 4
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> <script> let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); context.beginPath(); context.rect(10, 10, 100, 100); context.rect(50, 50, 100, 100); context.stroke(); </script> </body> </html>
원 예제 5
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px ; padding: 0px ; } </style> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> <script> let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); context.beginPath(); context.arc(100, 100, 80, 0, 2.0 * Math.PI, false); context.strokeStyle = "red"; context.stroke(); context.beginPath(); context.arc(100, 100, 60, 0, 1.5 * Math.PI, false); context.closePath(); context.strokeStyle = "blue"; context.stroke(); context.beginPath(); context.arc(100, 100, 40, 0, 1.5 * Math.PI, false); context.strokeStyle = "green"; context.stroke(); </script> </body> </html>
커브 예제 6
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> <script> let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); context.beginPath(); context.moveTo(90, 130); context.bezierCurveTo(140, 10, 288, 10, 288, 130); context.lineWidth = 10; context.strokeStyle = 'black'; context.stroke(); </script> </body> </html>
도형 예제 7
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> <script> let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); context.beginPath(); context.moveTo(50, 100); context.lineTo(75, 50); context.lineTo(100, 100); context.closePath(); context.fillStyle = "green"; context.fill(); </script> </body> </html>
텍스트 예제 8
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> <script> let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); context.font = 'italic 38pt Arial' context.fillText('Hello World!', 20, 100); </script> </body> </html>
그라디언트
• createLinearGradient(x, y, x1, y1) - 선형 그라디언트를 생성
• createRadialGradient(x, y, r, x1, y1, r1) - 원형 그라디언트를 생성
선형 그라디언트 예제 9
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> <script> let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); let gradient = context.createLinearGradient(0, 0, 200, 0); gradient.addColorStop(0, "white"); gradient.addColorStop(1, "red"); context.fillStyle = gradient; context.fillRect(10, 10, 180, 90); </script> </body> </html>
패턴 채우기 10
<!DOCTYPE HTML> <html> <head> .. </head> <body> <canvas id="myCanvas" width="1000" height="400"></canvas> <script> let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); let image = new Image(); image.src = "pattern.png"; image.onload = function () { let pattern = context.createPattern(image, "repeat"); context.rect(0, 0, canvas.width, canvas.height); context.fillStyle = pattern; context.fill(); }; </script> </body> </html>
이미지 그리기 11<body> <canvas id="myCanvas" width="600" height="400"></canvas> <script> let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); let image = new Image(); image.src = "html5_logo.png"; image.onload = function () { context.drawImage(image, 0, 0); }; </script> </body>
도형 변환
• 평행이동(translation)
• 신축(scaling)
• 회전(rotation)
• 밀림(shear)
• 반사(mirror)
• 행렬을 이용한 일반적인 변환
평행 이동 13
<body> <canvas id="myCanvas" width="600" height="400"></canvas> <script> let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); context.fillStyle = "blue"; context.fillRect(0, 0, 100, 100); context.translate(50, 50); context.fillStyle = "red"; context.fillRect(0, 0, 100, 100); </script> </body>
애니메이션 - Bouncing Ball 예제 14
<!DOCTYPE html> <html> <head> <title>Bouncing Ball Example</title> <style> canvas { background: yellow; border: 1px dotted black; } </style> <script> let context; let dx = 5; let dy = 5; let y = 100; let x = 100; function draw() { let canvas = document.getElementById('myCanvas'); let context = canvas.getContext('2d'); context.clearRect(0, 0, 300, 200); context.beginPath(); context.fillStyle = "red"; context.arc(x, y, 20, 0, Math.PI * 2, true); context.closePath(); context.fill(); if (x < (0 + 20) || x > (300 - 20)) dx = -dx; if (y < (0 + 20) || y > (200 - 20)) dy = -dy; x += dx; y += dy; } setInterval(draw, 10); </script> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> </body> </html>
벽에 닿으면 튕기는 Bouncing Ball 예제
'HTML' 카테고리의 다른 글
연습 예제 (0) 2023.10.20 요소 배치 (0) 2023.10.19 수평, 중앙, One True 정렬 레이아웃 (0) 2023.10.19 CSS3 속성 (0) 2023.10.06 CSS3 기초: 선택자와 단위 (0) 2023.10.05