Top Banner
153

CG&I web tech_workshop 28 June 2013

May 15, 2015

Download

Technology

Hwanyong Lee

KCC 한국종합컴퓨터학술대회 2013
여수 디오션 리조트
한국정보과학회 CG&I 소사이어티
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CG&I web tech_workshop 28 June 2013
Page 2: CG&I web tech_workshop 28 June 2013

차세대 웹 컨텐츠 기술 워크샵

장소 : 여수 디오션 리조트 에머랄드 A

일시 : 2013.6.28(금) 09:30 ~ 17:30

주관 : 컴퓨터 그래픽스 및 상호작용 소사이어티

조직 : 조직위원장 한정현(고려대)

프로그램 위원장 이환용(휴원)

시간 내 용 발표자

09:30-09:40 개회사 한정현(고려대)

09:40-10:30 HTML5 및 웹 앱 기술 동향 전종홍(ETRI)

10:30-10:45 휴식

10:45-11:35 Javascript Application 개발 기술 동향 박종일 (엠트리소프트)

11:35-12:25 CSS와 반응형 웹 기술 동향 신현석(SK플래닛)

12:25-13:30 중식

13:30-14:20 Web Graphics I : Canvas Element 이인균 (휴원)

14:20-15:10 Web Graphics II : SVG의 활용 윤지영(휴원)

15:10-15:25 휴식

15:25-16:15 Web Graphics III : WebGL 백낙훈(경북대)

16:15-16:30 휴식

16:30-17:30 CG & I 신진 연구 발표

Page 3: CG&I web tech_workshop 28 June 2013

HTML5 및 웹 앱 기술 동향

Jonghong JeonETRI, PEC

Email: [email protected] Blog: http://mobile2.tistory.com

http://twitter.com/hollobit

http://www.etri.re.kr

2

Growth of Web Sites

Total Sites Across All DomainsAugust 1995 - June 2013

http://news.netcraft.com/archives/2013/06/06/june-2013-web-server-survey-3.html

672,985,183 sites

Page 4: CG&I web tech_workshop 28 June 2013

Past : World Wide Web

4

In The Beginning .....

World Wide Web (Tim Berners-Lee, 1989) universe of network-accessible information anyone, anywhere, anytime Client to server interactions

Page 5: CG&I web tech_workshop 28 June 2013

5

WWW & Browser(Navigator)

6

Web Browser Architecture

Page 6: CG&I web tech_workshop 28 June 2013

7

FirefoxOS Architecture

8

Web Page Loading procedure

Page 7: CG&I web tech_workshop 28 June 2013

9

Web Page Loading procedure

10

Evolution of World Wide Web

Page 8: CG&I web tech_workshop 28 June 2013

11

Evolution of World Wide Web

1단계 (1989~1999) : 웹사이트의 시대, HTML과 WAP HTML, URL, HTTP 라는 세 가지 기술에 기초한 웹 기술이 제안되고, 보다

나은 인간 중심의 정보처리 및 지식공유 등을 목표로 하는 단계

2단계 (2000~2004) : XML과 웹서비스, 시맨틱 웹 XML(eXtensible Markup Language)에 기반하며 인간 중심의 정보 처리뿐 아

니라 다양한 디바이스와 서비스, 멀티미디어를 연결하는 것을 목표로 하는단계

3단계 (2005~2009) : 웹 2.0, 웹 플랫폼 시대의 성장 구글, 아마존, 위키피디아 등의 성공과 함께 웹 산업을 제2의 전성기로 이

끌며 다양한 신규 서비스가 등장할 수 있는 기반을 마련

4단계 (2010~현재) : 웹 앱의 시대, 모바일과 N-Screen 시대 스마트 폰 및 태블릿 등 다양한 모바일 기기들을 대상으로 HTML5와 Web

API를 통해 한 단계 진화된 웹 응용 환경을 제공하며, 위치정보 및 소셜 정보 등을 결합하는 통합 응용 플랫폼으로서 웹이 자리잡아 가는 단계

12

Evolution of World Wide Web

Page 9: CG&I web tech_workshop 28 June 2013

Now : HTML5 & Web Application

14

The History of HTML5 – emerging

2004 “WHAT” Working Group is born (Apple, Mozilla, Opera)

2006 W3C announces it will work with “WHAT” WG

2008 1st version of HTML5 is published (by Ian Hickson) HTML5 is a continually evolving technology that will never be

absolutely “finished”

2008 Firefox 3 becomes HTML5 compatible (Chrome, Safari, IE)

Reference: http://i2mag.com/wp-content/uploads/2012/07/TheHistoryofHTML5.gif

Page 10: CG&I web tech_workshop 28 June 2013

15

The History of HTML5 – growing

2010.1 YouTube offers HTML5 video Player

2010.4 Steve Jobs “trashes” Flash in an open letter

2010.5 Scribd documents switch to HTML5

2010.8 Arcade Fire’s HTML5-based interactive film is a hit

2010.12 Chrome Web Store opens

Reference: http://i2mag.com/wp-content/uploads/2012/07/TheHistoryofHTML5.gif

16

The History of HTML5 – explosion 2011.3 – Disney buys HTML5 gaming start-up “Rocker Pack” 2011.4 – FT, attracted more 2M users, 10 months after launch 2011.7 – Pandora begins moving to HTML5 2011.8 – Amazon creates Kindle Cloud Reader 2011.8 – Twitter rolls out new HTML5 version for iPad 2011.9 – 34% of Alexa’s top 100 sites use HTML5 2011.9 – Boston Globe opens subscription-only BostonGlobe.com

Uses responsive design and CSS3

2011.11 – Adobe stops making Flash for mobile devices 2012.4 – Flickr gets a new HTML5 uploader (large files) 2012.6 – LinkedIn creates 95% HTML5 native app for the iPad 2012.6 – Wix.com: +1M HTHML5 websites created by users

90 days after the publishing platform released its HTML5 website builder

2013.1 –+1B(1,000,000,000) HTML5-compatible smartphones

Reference: http://i2mag.com/wp-content/uploads/2012/07/TheHistoryofHTML5.gif

Page 11: CG&I web tech_workshop 28 June 2013

17

해외의 주요 HTML5 적용 서비스들

분야 이름 (개발사) 사이트HTML5 서비스

시작일

동영상

구글 YouTube http://www.youtube.com/html5 2010.01

Netflix http://www.netflix.com 2010.12

Vimeo http://vimeo.com 2010.01

문서

작업

SlideShare http://www.slideshare.net/html5 2011.09

구글 Docs http://docs.google.com 2010.04

구글 Gmail

구글 Clendar

http://www.gmail.com

http://google.com/calendar2011.09

소셜 Facebook’s Spartan 2011.08

전자책 Amazon Kindle https://read.amazon.com/ 2011.09

신문사 영국 Financial Times http://apps.ft.com/ftwebapp/ 2011.06

게임

Angry Birdshttp://chrome.angrybirds.com

http://facebook.angrybirds.com2011.05

Cut the Rope http://www.cuttherope.ie 2012.01

Fieldrunner http://fieldrunnershtml5.appspot.com 2011.10

18

HTML5 & Web App Technology Timeline

CSS1

Javascript

CSS2 CSS3

DOM1 DOM2 DOM3 DOM4

2010 2011

AJAX

HTTP

Canavs Web Workers AppCache

W3C

Web App.

Specs.

XHR2

WebGLGeolocation FileAPI

WebFontAudio/Video

Web form

2012 2013

HTTP2

HTML5 Working Draft

[email protected]

Page 12: CG&I web tech_workshop 28 June 2013

19

HTML5

HTML5로 통칭되는 요소는 HTML5 뿐 아니라 CSS3, 웹 어플리케이션을 위한 JavaScript API 확장을 포함한 것

통칭되는 “HTML5”

HTML5(Hypertext Markup Language 5.0)콘텐츠 내용과 형식을 표현

CSS3(Cascading Style Sheet 3.0)콘텐츠 표현 방법을 정의

JavaScript각종 API를 통해

기능을 표현

문서 구조의 의미를 명확히 하여디자인과 프로그램의 독립성을 확보

서로 다른 다양한 브라우저 상에서일관된 표현 기능 제공, 효과적이고 편

리한 표현 방식의 변경

풍부한 기능과 자원을 제어할 수있는 로컬 어플리케이션

문서구조의 상세화 멀티미디어 폼과 이벤트 등

표현 기능 모듈화 웹 폰트

Web Storage Web Worker Web Socket Geolocation API

20

HTML5

Web Application은 HTML, CSS, JavaScript의 협주곡

통칭되는 “HTML5”

HTML5콘텐츠 내용과 형식을 표현

CSS3콘텐츠 표현 방법을 정의

JavaScript각종 API를 통해

기능을 표현

문서 구조의 의미를 명확히 하여디자인과 프로그램의 독립성을 확보

서로 다른 다양한 브라우저 상에서일관된 표현 기능 제공, 효과적이고 편

리한 표현 방식의 변경

풍부한 기능과 자원을 제어할 수있는 로컬 어플리케이션

문서구조의 상세화 멀티미디어 폼과 이벤트 등

표현 기능 모듈화 웹 폰트

Web Storage Web Worker Web Socket Geolocation API

Page 13: CG&I web tech_workshop 28 June 2013

21

HTML5 ?

22

HTML5의 주요 특징

Offline / Storage Web SQL Database Local Storage IndexedDB Application Cache

Realtime / Communication Web Workers Web Socket Web Notifications

File / Hardware Access Native Drag & Drop Desktop Drag-In (File API) Desktop Drag-Out FileSystem APIs Geolocation Device Orientation Speech Input

Semantics & Markup Better semantic tags Markup for applications Descriptive link relations Microdata ARIA attributes

Web Form Graphics / Multimedia

<Video> / <Audio> Canvas 2D Canvas 3D (WebGL) Inline SVG

CSS3 CSS Selectors Web Fonts

Nuts & Bolts History API

Page 14: CG&I web tech_workshop 28 June 2013

23

The Web as an application platform

Standards for Web Applications on Mobile: Feb 2013 current state and roadmap http://www.w3.org/Mobile/mobile-web-app-state/

24

User Interactions

http://www.w3.org/2013/02/mobile-web-app-state/#User_interactions

Page 15: CG&I web tech_workshop 28 June 2013

25

Forms

http://www.w3.org/2013/02/mobile-web-app-state/#Forms

26

Device Adaptation

http://www.w3.org/2013/02/mobile-web-app-state/#Device_Adaptation

Page 16: CG&I web tech_workshop 28 June 2013

27

Graphics

http://www.w3.org/2013/02/mobile-web-app-state/#Graphics

28

Multimedia

http://www.w3.org/2013/02/mobile-web-app-state/#Multimedia

Page 17: CG&I web tech_workshop 28 June 2013

29

Sensors and hardware integration

30

Network

Page 18: CG&I web tech_workshop 28 June 2013

31

Communication and Discovery

Now : HTML5

Page 19: CG&I web tech_workshop 28 June 2013

33

<nav>

<header>

<canvas>

<ruby>

<article>

<video>

<audio>

<command>

<hgroup>

<dialog><details><datalist>

<footer><figure><embed>

<keygen> <mark>

<output>

<meter>

<section>

<source>

New HTML5 Tags

<aside>

<rp><rt>

http://dev.w3.org/html5/markup/elements.html#elements

34

<s> <strike>

<big>

<acronym>

<basefont>

<center>

<frame>

<font><dir>

<noframes>

<frameset>

<tt>

<u>

Removed Tags in HTML5

<applet>

Page 20: CG&I web tech_workshop 28 June 2013

35

Simplified Doctype

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

HTML5

<!DOCTYPE html>

HTML4/XHTML• HTML 4.01 Strict• HTML 4.01 Transitional• HTML 4.01 Frameset• XHTML 1.0 Strict• XHTML 1.0 Transitional• XHTML 1.0 Frameset• XHTML 1.1

36

Simplified Character Set

HTML4

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

HTML5

<meta charset=utf-8>

Page 21: CG&I web tech_workshop 28 June 2013

37

HTML5 Form

HTML5 의 새로운 input type들 Search, tel, url, email datetime, date, month, week, time, and datetime-local Number, range, Color

Mobile 에서 number, email, url 지원을 추가

placeholder attribute를 지원

<label for="email">Email address</label> <input id=“email” type="email" placeholder="[email protected]">

38

HTML5 Form - New input typesInput Type Purpose Notes

tel For entering a telephone number.tel does not enforce a particular syntax, so if you want to ensure a particular format, you can use pattern or setCustomValidity() to do additional validation.

search To prompt users to enter text that they want to search for.

The difference between search and text is primarily stylistic. Using an input type of search might result in the input field being styled in a way that is consistent with that platform’s search fields.

url For entering a single URL. url is intended for entering a single website address (absolute URL).

email For entering either a single email address or a list of email addresses.

If the multiple attribute is specified, then multiple email addresses can be entered, separated by commas.

datetime For entering a date and time with the time zone set to UTC.

date For entering a date with no time zone.

month For entering a date with a year and a month, but no time zone.

week For entering a date that consists of a week-year number and a week number, but no time zone.

time For entering a time value with hour, minute, seconds, and fractional seconds, but no time zone.

datetime-local For entering a date and time with no time zone.

number For numerical inputValid values are floating point numbers (whole and decimal numbers).

range For numerical input, but unlike number, the actual is not important.

The implementation of the range control is a slider in most browsers that support it.

color For choosing color through a color well control. The value must be a valid lowercase simple color such as #000000.

Page 22: CG&I web tech_workshop 28 June 2013

39

HTML5 Form - New input attributesAttribute Purpose Notes

autofocus Focuses the input on the element when the page is loaded.

autofocus can be applied to input, select, textarea,and button.

placeholder Gives the user a hint about what sort of data they should enter.

The placeholder value is displayed in light text until the element gets focus and the user enters some data. It can be specified on input and textarea.

form Specifies one or more forms to which the input element belongs.

By using the form attribute, the input elements can be placed anywhere on the page, not just within the form element. Also, asingle input element can be associated with more than one form.

required A boolean attribute that means the element is required.

The required attribute is helpful for doing browser-based validation without using custom JavaScript.

autocompleteFor specifying that a field should not autocomplete or be pre-filledby the browser based on a user’s past entries.

The autocomplete attribute for fields like a credit card number or one-time password, which you don’t want autocomplete. By default, autocomplete is in the on state, so if you want to disable it, set it to off.

pattern For validating an element’s value against a regular expression.

When using a pattern, you should also specify a title value to give the user a description of the pattern that’s expected.

dirname For submitting the directionality of the control with the form.

For example, if the user entered text data with right-to-left directionality and the input element contained the dirname attribute, then an indication of the right-to-left directionality would be submitted along with the input value.

novalidate For disabling form submission validation when specified on a form element.

formaction For overriding the action attribute on the form element.

This attribute is supported on input and button elements.

formenctype For overriding the enctype attribute on the form element.

This attribute is supported on input and button elements.

formmethod For overriding the method attribute on the form element.

This attribute is supported on input and button elements.

formnovalidate For overriding the novalidate attribute on the form element.

This attribute is supported on input and button elements.

formtarget For overriding the target attribute on the form element.

This attribute is supported on input and button elements.

40

HTML5 Revolution

Page 23: CG&I web tech_workshop 28 June 2013

41

42

HTML Standardization

WHAT-WG

Page 24: CG&I web tech_workshop 28 June 2013

43

HTML milestone

2012 2013 2014 2015 2016 2017 2018 2019 2020

HTML5.0 CR start …CR, LC REC … …

HTML5.1 FPWD --- LC + CR … CR REC

HTML5.x FPWD --- LC + CR … CR REC

HTML6.x FPWD --- LC + CR … CR REC

FPWD:First Public Working Draft LCWD: Last Call Working Draft PR: Proposed RecommendationWD: Working Draft CR : Candidate Recommendation REC: Recommendation

44

HTML5 Compatibility

http://html5test.com/results/desktop.html

http://html5test.com/results/mobile.html

Page 25: CG&I web tech_workshop 28 June 2013

45

HTML5 개발자 생태계의 성장

46

HTML5 관련 비즈니스 영역

Page 26: CG&I web tech_workshop 28 June 2013

47

HTML5의 현실과 이슈

48

웹 기술이 극복해야 할 요소들

Performance Engine enhance (Script, Rendering) H/W Acceleration Web OS

Offline HTML5 offline feature (application

cache, localStorage, online/offline events)

Device Capability Device APIs System Application APIs Web APIs (Web Intents, Web

Push…) Web OS

Monetization Web Application Store & Native

Web App

Developer Environment Developer Tools Javascript Frameworks

UI WebGL, Web Audio API CSS4, DOM4 Touch Events, GamePad API …

48

Page 27: CG&I web tech_workshop 28 June 2013

Future : Web App

50

Web UI의 변화, 현재와 미래

Sensors: Voice, Video, Sensing devices 카메라, 마이크, 터치, 가속, 자이로, 온도계, 위치, 제스처 …

M2M & Web of Things증강 브라우징, 위치기반 브라우징 …

Gopher

Keyboard

1차원Link

Mosaic

Mouse

2차원Link

PCIE

Mouse

Event

Mobile

Touch

Sensing

1995 2000 2005 2010

Page 28: CG&I web tech_workshop 28 June 2013

51

Web Platform Architecture

52

Emerging Web OS & HTML5 Apps

Page 29: CG&I web tech_workshop 28 June 2013

53

Native Web App

Native App

Web App

Web page

NativeWeb App

Hybrid Web App(Cross Platform)

Multi-platform support

54

Modern Web Applications

Various JS Frameworks & JS Library

http://www.slideshare.net/infect2/web-app-201205

Page 30: CG&I web tech_workshop 28 June 2013

55

Web App에 영향을 주는 요소 : 성능/시간

Web ApplicationsHTML5 Games

Native Web AppsBasic Web Pages

JavaScript Execution SpeedDOM Interactions

Accelerated Graphics

Page Load Time

http://channel9.msdn.com/Events/Build/2012/4-000?utm_source=javascriptweekly

56

JS 성능 개선을 위한 노력들

Developer Level Programming Best Practices & Tips

Engine Level Javascript Engine Race Javascript Interpreting mechanism Enhancement

Device Level Hardware Acceleration

• Web CL• GPU Acceleration

Performance Measuring & Benchmark

Page 31: CG&I web tech_workshop 28 June 2013

57

GPU Acceleration

IE

Chrome

Firefox

58

JongHong Jeon ([email protected]) +82-42-860-5333

http://mobile2.tistory.com/mhttp://twitter.com/hollobit

Page 32: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

CSS와 반응형 웹 기술동향

2013. 6. 28 KCC 2013 차세대 웹 컨텐츠 기술 워크샵SK planet, 신현석

http://hyeonseok.com

CSS3Cascading Style Sheets Level 3๏ 웹 콘텐츠의 표현 영역을 담당한다.

๏ 모듈화 되어 있어서 중요도에 따라 차별적으로 개발, 구현 된다.

๏ CSS3 개선점- 선택자(Selector)의 개선으로 다양한 방법으로 요소를 선택할 수 있다.

- 추가 이미지 자원 없이도 그림자 효과나 둥근 모서리와 같은 스타일을 적용할 수 있다.

- 폰트와 타이포그라피에 대한 지원이 향상되었다.

- 스크립트의 도움 없이 애니메이션 구현 가능하게 되었다.

Page 33: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

CSS3Cascading Style Sheets Level 3

text shadow

box shadow

border radius

border image

transition

2d/3d transform

font face

http://hyeonseok.com

CSS3Cascading Style Sheets Level 3๏ CSS2의 한계를 넘어서 다양한 레이아웃 제작 및 조정 관련 표준이제정중이다.

- CSS Multi-column Layout

- CSS Grid Layout

- CSS Flexible Box Layout

๏ 다양한 사용 환경에 능동적으로 대응하기 위한 표준이 제정중이다.

- Media Queries

- Responsive Image

Page 34: CG&I web tech_workshop 28 June 2013

http://www.slideshare.net/bryanrieger/rethinking-the-mobile-web-by-yiibu

http://hyeonseok.com

단말 다양성Devices Diversity๏ 다양한 단말기, 제조사

- 다양한 운영체제, 다양한 브라우저

๏ 다양한 화면 크기, 화면 밀도๏ 다양한 입/출력기기

다양한화면 크기 다양한 단말기

다양한 화면밀도

Page 35: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

단말 다양성Device independence๏ Density-independent pixel (dp)

๏ Responsive web design

고정 픽셀 dp

http://hyeonseok.com

모바일 환경에 대응단말별 최적화?

๏ 99.9% 고객 문의 이메일이 자신의 단말기가 지원되지 않는다는 내용이다. 우리는 현재 707개의 단말기를 지원하고 있다. 멘붕...

http://thenextweb.com/mobile/2012/03/30/the-shocking-toll-of-hardware-and-software-fragmentation-on-android-development/

Page 36: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

모바일 환경?Mobile context?๏ 77%의 모바일 검색은 집이나 사무실에서 한다.

http://googlemobileads.blogspot.kr/2013/03/mobiles-immediacy-effect-half-of-mobile.html

http://hyeonseok.com

모바일 환경?Mobile context?๏ 90%의 사용자가 과업을 수행하기 위해서 여러 화면(기기)을 연속해서 사용한다.

http://www.google.com/think/research-studies/the-new-multi-screen-world-study.html

Page 37: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

반응형 웹디자인에 대한 관심Why You Need to Prioritize Responsive Design Right Now๏ "반응형 디자인의 우선순위를 높여야 할 때이다."

๏ "모바일 사이트에 원하는 정보가 없을 경우 당황하게 된다."

๏ "SEO나 마케팅을 간단하게 해주고 단일화 할 수 있다."

๏ "모바일 페이지와 데스크탑 페이지가 동일한 URL을 갖기 때문에검색 순위에서 상위를 차지할 수 있다."

๏ "단말기별, 해상도별 코드를 만들 필요가 없다. 값비싼 백엔드 솔루션도 필요 없다."

http://www.forbes.com/sites/work-in-progress/2013/03/26/why-you-need-to-prioritize-responsive-design-right-now/

http://hyeonseok.com

CSS 미디어 쿼리CSS3 Media Queries๏ CSS2 미디어 타입에 미디어 상태(media feature)를 추가하여 다양한 단말기에서의 표현을 제어할 수 있게 고안된 기능이다.

๏ Opera Software에서 처음 제안하였다.

๏ 표준화 되었고 대부분의 브라우저에서 지원하고 있다.

- W3C Recommendation 19 June 2012

@media screen and (max-device-width: 480px) { /* mobile optimization */}

Page 38: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

미디어 쿼리CSS3 Media Queries๏ 단말기의 화면 폭에 따라서 서로다른 스타일을 적용할 수 있다.

๏ 현재의 상황이 조건에 맞으면 선언된 스타일이 적용되고 맞지 않거나 알 수 없으면 false가 리턴된다.

@media screen and (max-width: 320px) { body { background-color: #00F; }}@media screen and (min-width: 321px) and (max-width: 800px) { body { background-color: #F00; }}@media screen and (min-width: 801px) { body { background-color: #0F0; }}

http://mydeute.com/txp/article/631

http://hyeonseok.com

미디어 쿼리CSS3 Media Queries๏ 이외에도 많은 미디어 상태(media features)를 사용할 수 있다.

width 화면의 너비height 화면의 높이

device-width 단말기의 너비device-height 단말기의 높이orientation 화면의 가로/세로 모드aspect-ratio 화면 비율

device-aspect-ratio 단말기 화면 비율color 색상 비트수

color-index 색상 테이블 엔트리 수monochrome 모노크롬 프레임 버퍼의 픽셀당 비트수resolution 화면 해상도

scan TV의 스캔 방식grid 그리드/비트맵 방식 여부

http://www.w3.org/TR/css3-mediaqueries/

Page 39: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

미디어 쿼리Media Queries Browser Supports

http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(Cascading_Style_Sheets)

http://m.naver.com

Page 40: CG&I web tech_workshop 28 June 2013

http://engdic.daum.net/word/view.do?wordid=ekw000139806&q=responsive

http://movie.naver.com/movie/bi/mi/basic.nhn?code=74873

Page 41: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

가변폭 콘텐츠Flexible Contents๏ 컬럼의 너비가 변경되어도 웹 페이지 안의 미디어가 컬럼을 넘치지않게 해야 한다.

๏ max-width를 지원하지 않는 인터넷 익스플로러를 위한 스크립트도 공개하고 있다.http://unstoppablerobotninja.com/entry/fluid-images

http://www.alistapart.com/articles/fluid-images/

img, embed, object, video { max-width: 100%;}

http://hyeonseok.com

가변폭 콘텐츠Image Text๏ 이미지 텍스트는 가변폭 이미지를 사용했을 때 작은 화면에서 가독성이 매우 떨어진다.

๏ 이미지 텍스트를 피하고, 기본 서체나 웹 폰트를 사용한다.

๏ 전송량이 매우 크고, 지원도 잘 안되기 때문에 모바일에서는 웹 폰트 사용을 피한다.

@font-face { font-family: Nanumpan; src: url('NanumPen.ttf');}span { font-family: Nanumpan, sans-serif;}

Page 42: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

가변폭 콘텐츠Responsive Box๏ 동영상이나 일반 박스의 가로세로 비율을 유지하는 방법이다.

๏ 패딩이나 마진을 퍼센트로 지정하면 비율을 유지할 수 있다.

#movie-player-wrapper { position: relative; width: 100%; height: 0; overflow: hidden;

padding-bottom: 56.26%;}#movie-player-wrapper .wrap { position: absolute; top: 0; left: 0; width: 100%; height: 100%;}

http://hyeonseok.com/soojung/css/2012/08/22/712.html

http://hyeonseok.com

가변폭 콘텐츠Responsive Data Tables๏ 좁은 화면에서 데이터 테이블의 가독성이 낮다는 문제를 해결하기위한 방법이다.

๏ 테이블의 데이터를 선형화해 한줄로 푼다.

http://css-tricks.com/9096-responsive-data-tables/

linearization

table, thead, tbody, th, td, tr { display: block;}

Page 43: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

가변폭 콘텐츠Responsive Table๏ Responsive Data Tables의 단점을 보완한 방법이다.

๏ 테이블의 데이터를 스크롤 가능하게 만들어준다.

http://www.zurb.com/playground/responsive-tables

<link type="text/css" media="screen" rel="stylesheet" href="responsive-tables.css" /><script type="text/javascript" src="responsive-tables.js"></script>

http://hyeonseok.com

가변폭 콘텐츠반응형 테이블๏ CSS 추가 수정 없이 테이블 정보의 선형화에 초점을 둔 방법이다.

- JavaScript로 셀 헤더 정보를 data-cell-header 속성에 저장하고 이를 CSS를 통해서 화면에 출력하는 방법

http://hyeonseok.com/soojung/webstandards/2013/03/09/729.html

Page 44: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

성능Performance๏ 단일한 HTML로 모든 종류의 기기를 대응해야 한다.

๏ 실제 사용되는 이미지보다 더 큰 이미지를 사용할 수 있다.

๏ 이미지 리사이징은 단말기의 CPU를 보다 더 많이 사용한다.

๏ 사용하지 않는 자원(이미지, CSS)을 전송 받을 수 있다.

๏ 미디어 쿼리를 지원하지 않는 브라우저의 사용자가 많다.

http://hyeonseok.com

성능Server side approach๏ User Agent Sniffing

- 브라우저의 사용자 에이전트 문자열로 단말기를 판별

๏ Device Description Repository

- 단말 정보 저장소의 정보로 단말기를 판별

๏ 장점- 비교적 정확하고 클라이언트 성능 문제가 없다.

๏ 단점- 다양한 단말기의 종류를 지속적으로 관리하고 성능을 파악하고 있어야 한다.

Page 45: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

성능RESS: Responsive Design + Server Side Components

๏ 콘텐츠 모듈을 서버에서 구분하여 전송하는 방법이다.

๏ User Agent Sniffing과 반응형 웹디자인 개념을 적절히 혼합한 개념이다.

๏ 사용자 에이전트 문자열 판별이 가장 큰 단점이다.

http://www.lukew.com/ff/entry.asp?1392

http://hyeonseok.com

성능Responsive Image๏ 이미지는 콘텐츠는 미디어 쿼리나 JS 등으로 지정하기 힘들다.

๏ 단말 해상도별 이미지를 마크업 레벨에서부터 최적화하고자 하는다양한 시도가 진행중이다.

- Adaptive Images(http://adaptive-images.com)

- Apache 2 + PHP 5.x + GD lib * + JS

- HiSRC(https://github.com/teleject/hisrc)

- data-attribute + div.hisrc + jQuery plugin

- Picturefill(https://github.com/scottjehl/picturefill)

- div[data-picture], div[data-alt], div[data-src] + picturefill.js

- Responsive Enhance(https://github.com/joshje/Responsive-Enhance)

- img[data-fullsrc] + responsive-enhance.js

Page 46: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

성능Responsive Image Community Group๏ W3C 커뮤니티 그룹

- picture + img[srcset]

http://responsiveimages.org

http://hyeonseok.com

CSS 다단 레이아웃CSS Multi-column Layout๏ 텍스트를 다단으로 배열한다.

๏ 텍스트가 변경되어도 자동으로 다단을 연결해준다.

๏ W3C Candidate Recommendation 12 April 2011

http://www.w3.org/TR/css3-multicol/

column-count: 3;column-gap: 1em;column-rule: 1px solid black;

Page 47: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

CSS 그리드 레이아웃CSS Grid Layout๏ 화면 레이아웃을 구성할 때 그리드의 위치와 크기, 그리드 안에 들어갈 요소를 선언하여 유연한 화면 크기에 대응할 수 있게 해준다.

๏ 윈도우 8 애플리케이션 제작에 사용할 수 있다.

๏ 콘텐츠의 순서에 상관없이 자유롭게 콘텐츠를 배치할 수 있다.

http://www.w3.org/TR/css3-grid-layout/

http://hyeonseok.com

CSS 그리드 레이아웃CSS Grid Layout๏ 부모 요소를 그리드로 선언한다.

๏ 자식요소들을 그리드 안에 배치한다.

.wrapper { display: -ms-grid; -ms-grid-columns: 200px 25px 1fr; -ms-grid-rows: 160px 25px 1fr 25px 200px;}

#logo { -ms-grid-row: 1; -ms-grid-column: 1;}#menu { -ms-grid-row: 3; -ms-grid-column: 1; -ms-grid-row-span: 3;}

#main { -ms-grid-row: 1; -ms-grid-column: 3; -ms-grid-row-span: 3;}#nav { -ms-grid-row: 5; -ms-grid-column: 3;}

http://msdn.microsoft.com/en-us/library/ie/hh673533(v=vs.85).aspx

Page 48: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

CSS 유동 박스 레이아웃CSS Flexible Box Layout๏ Flex layout이라는 개념을 도입하여 박스의 정렬과 사이 간격을 효율적으로 정의할 수 있게 해주는 기능이다.

http://www.w3.org/TR/css3-flexbox/

http://hyeonseok.com

CSS 유동 박스 레이아웃CSS Flexible Box Layout

http://css-tricks.com/snippets/css/a-guide-to-flexbox/

justify-content align-items

Page 49: CG&I web tech_workshop 28 June 2013

http://hyeonseok.com

CSS3 사용의 이점Benefits๏ 이미지 자원을 최소화하여 네트웍 부담을 줄일 수 있다.

๏ 비트맵 이미지를 줄이고 백터 이미지를 사용할 수 있어서 고집적도단말기에 대한 대응이 용이하다.

๏ 다양한 레이아웃 기법을 지원해서 높은 성능을 기대할 수 있다.

๏ 표준에서 정의한 대체 동작을 활용해서 저사양 단말기의 사용환경과 성능에 적절한 사용자 경험을 제공할 수 있다.

http://hyeonseok.com

감사합니다http://hyeonseok.com/,

[email protected]

Page 50: CG&I web tech_workshop 28 June 2013

1

1

2013.06

대표이사 박종일

2

목차

I. HTML5 표준 기술

II. JavaScript History

III. JavaScript Library(Framework)

IV. 최신 JavaScript 적용 기술 사례

V. 맺음말

Page 51: CG&I web tech_workshop 28 June 2013

2

3

• 전자, 컴퓨터공학, 지식경영 전공(숭실대 공학석사)

• 現 ㈜엠트리소프트 대표이사

• 現 환경부 모바일 서비스 정보화 전략계획 PM

• 現 모바일 웹 포럼 표준기술위원

• 現 앱센터 기술 분야 자문위원

• 現 TTA PG6051 모바일웹 표준 실무반 위원(Device API)

• 現 TTA 표준화 전략 로드맵 스마트미디어 분야 Editor

• 現 플랫폼 전문가 그룹 운영진(http://platformadvisory.kr)

• 現 T아카데미 웹앱 개발 강의 및 서비스 멘토링(웹 기술 관련 다수 대학 강의)

• 現 KEIT 임베디드 분야 기술 과제 심사 위원

• 前 CJ제일제당 통합 R&D 센터 ICT 컨설팅 PM 외 다수 ISP 컨설팅 수행

• 前 WBS 웹 응용 프레임워크 개발 PM

• 前 포비커 사업총괄 이사(더매거진, 라쿠텐, 글로벌 SNS, 스포츠토토 모바일)

• 前 지어소프트 컨버전스 2팀 부장(Android UI Builder 개발 PM)

• 前 어니언텍 신사업, LBS 사업팀 차장(MAPOT, 서울시 u-Tour, CRBT)

• 前 엠커머스 플랫폼 개발팀(BREW, WIPI 1,2차 과제 PM)

발표자 소개

4

I. HTML5 표준 기술

Page 52: CG&I web tech_workshop 28 June 2013

3

5

스마트 시대!

• Smart Platform은 모바일을 시작으로 홈, 자동차, 학교, 도시로 적용 대상과 사업 영역을 확장하고 있음

OS, Platform Integration

2015 2012 2009

WiFi+3G WiFi(Direct)+ LTE(advanced) Beyond 4G Network

Device

Service Content Delivery Cross(life) Connected artificial intelligent Service

• Smart Phone

• Tablet

• E-Book

• 게임기

• Smart TV, 가전(Home)

• Smart Car

• Smart Education

• Smart Work

• Smart Payment

• Smart Health

• Smart Glass, Watch

• 도시, 교통, 환경, 식량

• 생산(공장), 유통(도소매)

• 에너지, 중공업(조선, 플랜트)

• 공공 분야

• IoT(internet of things)

Dual-Core(GPU 별도) Quad-Core(SoC) 1.7Ghz Octa-Core up to 2.0GHz

Content Personal + Info Media + Big data Semantic Data

범용화, 융합화, 지능화

Smart Platform

Micro Platform

Platform 적용분야

UI/UX Multi Touch UI Speech(Object) Recognition Context Awareness

NOW

Redefine

6

플랫폼 춘추 전국 시대

Open & Close Source Global Standard

Fast & Easy Development Tool 제공

다양한 응용 API 지원

HW, SW, NW 최신 사양 지원

Developer Community 적극 지원

멀티 터치 HI(Human Interface)

Open & Close Market(Store)

Fragmentation

플랫폼 차별화 진행

“Write

Once

, Run E

very

where

!”

Page 53: CG&I web tech_workshop 28 June 2013

4

7

What is HTML5?

• 단순 Web 페이지에서 Web Application 으로 진화

• HTML5는 현재 사용되는 HTML의 다음 버전

• WWW를 구성하는 핵심 마크업 언어

• 브라우저 기반 동일한 실행 환경

• N-Screen 대응

• 웹 기술 표준화

8

What is HTML5?

MOBILE

HTML WG

Canvas, CSS3, 3DTransforms,

SVG, WebGL

MediaStream Processing API,

Web Audio, Media Capture

Web Events Working Group,

Touch Events API

Device API WG

Geolocation WG

HTML WG

Web Messaging API,

WebSocket API,

Server-Sent Events API,

XMLHttpRequest Level 2

Web Storage, File API,

Indexed Database API

HTML5 Application Cache,

Widget Packaging,

Web Application Security WG

• HTML5는 Web Application을 지원하기 위한 다양한 API 지원

Page 54: CG&I web tech_workshop 28 June 2013

5

9

HTML5 History

• HTML5는 2013년 Last Call for Review 단계로 명확한 표준 범위 정의

1991 HTML

1994 HTML2

1996 CSS JavaScript +

1997

1998

HTML4

CSS2

2009 HTML5

2005 AJAX

2000 XHTML

XHTML2 WG 2002

WHATWG 2004

2007 HTML5 WG

2010

2014

XHTML 표준화 중단

오페라, 모질라, 애플

HTML5 WD

HTML5 REC

10

Web 기술의 발전

• How Browsers Work

http://www.html5rocks.com/en/tutorials/internals/howbrowserswork

[Rendering engine basic flow]

[Webkit main flow] [Bowser main components]

Page 55: CG&I web tech_workshop 28 June 2013

6

11

Web 기술의 발전

• 자바스크립트 엔진 성능 향상

Mozilla의 Trace-Monkey, Google의 V8, Apple의 SquirrelFish Extreme JIT(Just In Time) Compilation를 통한 Interpreter 방식이 아닌 머신코드로 컴파일

12

What is HTML5?

• 구조화된 문서 형태(Semantic)

• 다양한 기능 구현 가능(Application Program Interface)

http://html5.clearboth.org/spec

Page 56: CG&I web tech_workshop 28 June 2013

7

13

New Markup Elements

• for better structure, media content, drawing

• New Form Elements and input type attribute values

14

HTML5 Features

• HTML5를 구성하는 주요 기술 요소

3D Effect

Connectivity Device Access

Multimedia

Offline & Storage

Performance

Semantics

CSS3

http://mobilehtml5.org/ http://html5test.com/

HTML5 ~= HTML + CSS + JS

HTML5 = Next Generation Features for Modern Web Development

Page 57: CG&I web tech_workshop 28 June 2013

8

15

HTML5 Features | Semantics

• Common structures

• Semantic meaning(RDF, microdata, microformats, ...)

• What is the potential of new elements?

– eg. Search engine, ...

HTML4 HTML5

16

HTML5 Features | Semantics

• What is added in HTML5? – email, url, number, range, date, month, week, time, datetime,

datetime-local, search, color, ...

Page 58: CG&I web tech_workshop 28 June 2013

9

17

HTML5 Features | Offline & Storage

• Web apps need to work everywhere

• Database and app cache store user data and app resources locally

18

HTML5 Features | Offline & Storage

• Database right in the browser

• Around 5MB per domain

• Accessible across tabs and windows

• Based on SQLite

• Features: Transaction, SQL queries

• Key/value pair storage

• Hash-based storage of strings (not objects)

• 10MB per zone

• 2 way types

• sessionStorage: • Die when browser is closed

• Not shared between tabs

• localStorage • Crash-safe

• Shared BW tabs/windows and sessions – but not zones

Web DB Indexed DB

Page 59: CG&I web tech_workshop 28 June 2013

10

19

• 웹 페이지가 실행되는 단말(PC, 스마트폰, ...) 위치 정보 획득 가능

• 사용자 허가가 있어야 함

HTML5 Features | Device Access

• Geolocation API – Bring browser-based location to your apps

20

HTML5 Features | Device Access

• Device API – PIMS(Contact, Calendar, Memo), Camera, Sensor..)

http://www.youtube.com/watch?v=jqXo-AEVhK4

• Nodejs와 WebSocket으로 DeviceAPI를 지원하는 모바일과 PC를 연동, getUserMedia 를 통해 stream data를 video 태그로 전송

Page 60: CG&I web tech_workshop 28 June 2013

11

21

• Web Socket – TCP for the Web

– A next-generation bidirectional communication tech. for the web apps

HTML5 Features | Connectivity

– 실시간 통신 가능

– 서버측 구현은 별도로 필요

22

• What is Canvas? – Dynamic and interactive graphics

– Draw images using 2D drawing API

• Lines, curves, shapes, fills, ...

– Useful for graphs, applications, games, ...

HTML5 Features | Canvas

Page 61: CG&I web tech_workshop 28 June 2013

12

23

• What is SVG? – Scalable Vector Graphic

– HTML-like markup tags(XML) for drawing

– Adobe Flash, MS Silverlight 등 대체 가능

HTML5 Features | SVG

24

HTML5 Features | Audio/Video

• HTML5는 별도의 플러그인 없이 브라우저에서 멀티미디어 재생 가능

• 오디오/비디오를 제어하기 위한 자바스크립트 API 제공

• <audio>, <video> 태그만으로 HTML 페이지에 멀티미디어 삽입 가능

• play(), pause(), ... 등 자바스크립트 API로 비디오 콘텐츠 제어 가능

• VideoJS(http://videojs.com/), Audio.js(http://kolber.github.com/audiojs/)

Page 62: CG&I web tech_workshop 28 June 2013

13

25

HTML5 Features | Audio/Video

• 최근 구글이 WebM 공개 코덱 발표

• 코덱과 관련된 특허 문제 해결 시급

• 브라우저 별로 코덱 지원 사양이 다를 수 있음

• 비디오 코덱은 W3C와 별도로 라이센스 이슈 있음

MPEGLA 와 Google WebM(VP8) 이슈

HTML5 Video Player Comparison : http://j.mp/dfxNMQ

26

HTML5 Features | Web Workers

• 일반 프로그래밍 언어에서 제공하는 쓰레드와 동일

• 롱타임 작업은 워커가 담당

Webworkers Demo : http://html5demos.com/worker

•API for running background scripts(긴 문서의 문자 서식지정, 이미지 프로세싱, 이미지 합성, 배열 처리, 복잡한 수식 계산) •Threads for the web apps •Browser support - if(!!window.Worker)

•Firefox 3.5 ~ •Safari 4 ~ •Chrome 4

•Useful for gaming, graphs, crypto, ... •Limits

•DOM 접근 제한 •document, getElementById, ...

•‘parent’ page 접근 제한 •Javascript 변수, 메소드 접근 불가

Page 63: CG&I web tech_workshop 28 June 2013

14

27

HTML5 Features | CSS3

• Animation 효과를 통한 다이나믹한 화면 구성

• CSS3를 이용한 이미지 대체 가능

• Responsive Web Design 가능

• 현재 계속 개발 중(code.google.com/p/css3-mediaqueries-js/)

• 마크업 언어가 실제로 출력되는 방법 명세

http://www.w3.org/TR/css3-mediaqueries/

28

HTML5 Features | CSS3

• 하나의 CSS로 모든 화면을 처리할 경우 불필요한 스타일 데이터를 기기에 다운로드 하게 됨

<link rel="stylesheet" type="text/css" href="stylesheets/base.css"

media="screen, handheld" />

<link rel="stylesheet" type="text/css" href="stylesheets/desktop.css"

media="only screen and (min-width: 720px)" />

<link rel="stylesheet" type="text/css" href="stylesheets/mobile.css"

media="only screen and (min-width: 320px)" />

MAJOR BREAKPOINTS IN DOCUMENT HEAD

Page 64: CG&I web tech_workshop 28 June 2013

15

29

II. JAVASCRIPT HISTORY

30

JavaScript History

• 넷스케이프 브라우저 스크립트로 시작, 자바 언어의 흥행 영향을 받아 JavaScript로 명명

Sun MicroSystem

SIG(실리콘그래픽스) “Brendan Eich” 현재 Mozilla CTO

넷스케이프에 입사 하는 조건으로 10일 안에 함수형 언어를 브라우저에서 동작하게 하겠다.

MS IE3 JScript에 대응하기 위한 표준화

Mocha LiveScript JavaScript

1995년 9월 1995년 12월

Ecma International

ECMA-262 3판 (JS 1.5)

ECMA-262 5판 (ES 3.1)

1999년 12월

2011년 06월

EcmaScript Harmony

현재

Java(Applet) 탑재 실패

Page 65: CG&I web tech_workshop 28 June 2013

16

31

ECMAScript

• ECMA(European Computer Manufacturers Association), 컴퓨터 시스템 표준 및 개발 언어 표준 정의

ECMA Script First

• 기본적인 문법

• 기본적인 연산자

• 기본적인 개체

• 명세서도 자체도

허술

ES2

• ISO/IEC 제출용

ES3

• 정규식 소개

• String 객체

• try/catch 예외처리

• 오류처리 주위

• 본격적으로 브라우저

적용

• Adobe 지원

ES5

• ES3.1 기반

• strict 모드

• JSON 지원

• 속성접근 주위

ES4

32

III. JAVASCRIPT LIBRARY

Page 66: CG&I web tech_workshop 28 June 2013

17

33

JavaScript Library

• 웹 기술의 발전 및 다양한 요구에 따라 JavaScript는 기술적 역할 확대

http://www.remotesynthesis.com/post.cfm/50-javascript-html5-frameworks-and-related-tools

DOM 탐색 및 제어

HTML 요소 변경

데이터의 유효성을 검사

방문자의 브라우저를 감지

쿠키의 저장, 검색

API(WebSocket, Canvas, WebGL, Geolocation…)

CSS 접근 및 변경(Responsive Web)

Widget Drawing(Tabs, Tree, Chart..)

단말을 제어하기 위한 기능

UI Effect 이벤트 제어 및 애니메이션

HTML DOM Tree접근 및 변경(Selector)

AJAX를 통한 비동기 통신

자바스크립트 역할 JavaScrpit vs Java

34

JavaScript Library

• 다양한 모바일 및 웹 서비스 개발 지원을 위한 JS Library가 개발되고 있음

jQuery와 JQuerymobile을 활용한 서비스 사례

1. 터치 스크린 장치에 최적화 : 대신 마우스 커서의 입력 장치로 손

가락 사용자 인터페이스 지원.

2. 모바일 웹 개발 프레임워크 : 모바일 장치 플랫폼을 위해 특별히

표준 UI 요소 및 이벤트 처리 제공

3. 크로스 플랫폼 : 다양한 모바일 디바이스 플랫폼에 대한 지원 등

IOS와 안드로이드는 사용자의 다양한 앱 개발 지원

4. 경량 : 현재의 대역폭 제한으로 인해 리소스 및 기능 파일의 용량

을 제한적으로 제공

5. HTML5와 CSS3 표준을 사용 : 대부분의 주류 모바일 장치를 지원

하고 최신 웹(모바일)브라우저에서 HTML5와 CSS3 등 W3C의 새

로운 표준 사양을 사용할 수 있는 기능을 제공

Source : http://sixrevisions.com/javascript/mobile%C2%A0web-development-frameworks/

Page 67: CG&I web tech_workshop 28 June 2013

18

35

JavaScript Web Framework

• Ajax 기술을 활용한 다양한 오픈 소스 JavaScript Framework 개발

항목 JQuery Sencha

개발 난이도 (용량)

보통(80k) 높음(360k)

표현 자유도 (확장성)

보통 높음

지원 기능 많음(동영상, 차트..) 아주 많음(동영상, 3D, 차트,

개발 방식 마크업 기반 스크립트 기반 객체 개발

테마 특징 테마 롤러 도구 지원 (페이지별 JS 로딩)

Sass- Sassy CSS(초기 JS를 모두 로딩 하여 최초 구동 속도가 다소 느림- CSS를 별도 프로그램 형식으로 개발)

기반 스크립트 Lib JQuery ExtJS

지원 기기 iOS, Android, 블랙베리, HP WebOS, 오페라, Firefox mobile (스마트폰, 태블릿 지원)

iOS, Android, 블랙베리 (스마트폰, 태블릿 지원)

• Microsoft Ajax Control Toolkit(http://ajax.asp.net) • Google Web Toolkit(http://code.google.com/webtoolkit)

• Dojo(http://dojotoolkit.org/) • Magic Framework(http://www.jeffmcfadden.com)

36

다양한 jQuery UI 및 테마

jQuery

• jQuery(http://jquery.com)- 2013.06 현재 ver 1.10.1

MIT, GPL v2 듀얼 라이센스

클라이언트 사이드 자바스크립트 라이브러리, Ajax 개발 용이

모바일 적용을 위한 jQuery Mobile을 통한 터치 이벤트 지원 및 다양

한 UI 테마 제공

애니메이션, 이벤트 제어, CSS등 Responsive 웹 제작을 위한 최적의

솔루션

• Ajax로 시작된 인터렉티브 웹 사이트는 최근 웹 어플리케이션 형태로 진화

• jQuery는 다이나믹 웹 및 모바일 지원을 강화하면서 사용자 층 확대

Eclipse jQuery 설정 : http://kinjsp.pe.kr/lecture/eclipseJQuery.kin http://menguy.tistory.com/532

Page 68: CG&I web tech_workshop 28 June 2013

19

37

jQuery

• JQuery는 다양한 Plug-in을 통해 기능 확장을 지원하고 있음

• Plug-in Archive를 통해 다양한 type의 Plug-in 프로젝트 관리

• Ajax • Animation and Effects • Browser Tweaks • Data • DOM • Drag-and-Drop • Events • Forms • Integration • JavaScript • jQuery Extensions • Layout • Media • Menus • Metaplugin • Navigation • Tables • User Interface • Utilities • Widgets • Windows and Overlays

PROJECT TYPES

http://speckyboy.com/2010/08/22/50-awesome-new-jquery-plugins/ http://speckyboy.com/2011/12/07/the-50-most-useful-jquery-plugins-from-2011/

Isotope is a jQuery plugin for intelligent, dynamic layouts.

Diapo is a free jQuery slideshow plugin. It is an open source project.

38

jQuery

• 데이터와 디자인 분리, 기능과 데이터(JSON)를 분리

• jQuery는 다양한 플러그인으로 확장

가장 Simple 하면서 강력한 자바스크립트 라이브러리

- 적은 용량 : 31kb, 개발자 코드 229kb

- Built around CSS selectors

- 강력한 개발자 커뮤니티

- 현재 100대 웹 사이트에서 사용, 기술 서적 제공

문서 객체 처리 기능

- 웹 문서 내 객체 접근

- 웹 문서 이벤트 핸들링 용이

다양한 기능 제공

- 애니메이션 기능 추가 가능

- Ajax 기능 사용 가능

- 기존 브라우저에 대한 호환성 지원

- Plug-in을 통한 확장( jQueryMobile, jQuery Visualize)

* Pure JavaScript divs =document.getElementByTagName*’div’); for(i=0; i<divs.length; i++){ divs[i].style.display =‘none’ } <head> <script type="text/JavaScript" src="jquery-1.4.2.min.js"></script> </head> $(“div”).hide();

Building the JavaScript

$(‘#menu’).addClass(‘hello’) jQuery Object

Find some Element

Do something with item

Page 69: CG&I web tech_workshop 28 June 2013

20

39

• Sencha(http://www.sencha.com)

HTML5 표준을 준수하는 Ext JS 기반의 모바일 웹 어플리케이션용 JS 프레임워크

Sench Touch 를 통한 모바일 디바이스 지원, 전용 개발 도구 지원

도표 제작 및 엔터프라이즈 지원 강화

Sencha.io: 클라우드 기반으로 다양한 스크린 사이즈의 디바이스에 대응

PhoneGap 등 하이브리드 웹 앱 프레임워크와 연동

네이티브 수준의 터치 이벤트 처리 Sencha로 개발한 카드 게임 Sencha.io 개념도

Sencha

• Sencha는 Ext.JS로 시작한 자바 스크립트 프레임워크로 PC & Mobile 지원

• 완성도 높은 웹 앱 프레임워크로 다양한 상용 제품군 확보

40

Sencha

• ExtjS 라이브러리를 기반으로 개발, ExtJS의 API 구조와 문법 체계를 계승

• 향후 SVG, VML을 기반으로 하는 Raphael을 통합하여 제공 예정

•ExtJS 라이브러리를 기반으로 개발

• 대부분의 소스코드는 JavaScript와 ExtJS 라이브러리로 구성

• Component Panel 기반(Java SWING과 유사)

• 자유도가 높은 ExtJS 스터디 필요

• Native앱과 유사한 UI를 제공

• JQueryMobile은 TOP/Bottom 영역에 고정바를 둘 수 없음(수정 가능)

• 통신 모델

• 기본적으로 URL이 1개뿐(특정 페이지를 직접 URL 입력으로 접근 시 추가 작업이 필요)

• 두번째 페이지 부터는 Ajax 통신을 이용해 화면을 로딩

• 데이터 핸들링은 JSON을 활용

• JQueryMobile vs Sencha Touch

• 기존 웹페이지를 모바일로 변경할 경우 JQueryMobile 사용이 유리

• 강력한 Native 앱과 유사한 서비스를 신규로 개발할 경우 Sencha Touch 사용

Page 70: CG&I web tech_workshop 28 June 2013

21

41

Kendo UI

• 상용 HTML5 UI Lib(1년 399$)로 JQuery보다 빠른 성능과 기술 지원 가능

• 풍부한 HTML5와 Grid등 기업용 UI 위젯, 강력한 데이터 소스, 터치 지원

Mobile Device Compatibility

• Android 2.0+

• iOS 3.0+

• BlackBerry OS 6.0+

• WebOS 2.2+

Supported browsers

• Internet Explorer 7+

• Firefox 3+

• Safari 4+

• Chrome

• Opera 10+

42

BootStrap

• 가볍고 간단한 오픈소스 기반 (아파치2.0 라이센스)의 HTML5, CSS3 UI 프레임워크

• 레이아웃과 기본 탬플릿을 통해 가장 쉽고, 빠르게 Responsive Web 기반 서비스를 구축할 수 있음

• 기본 사항

• 많은 사이트에서 사용(안정성 검증)

• 설치까지 JS, CSS만 연결하면 사이트 완성

• 직관적인 UI와 쉬운 구조(사이트 단순)

• UI(Componets)

• 기본 CSS 기반 UI 컴포넌트 지원

• 별도 테마를 쓸 경우 멀티 디바이스를

지원하지 않을 수 있음

• JQuery UI Plug-in

• 커스터마이즈 기능을 기본으로 제공

• JQuery Plug-in 기능 지원

(http://addyosmani.github.io/jquery-ui-bootstrap/)

• http://www.initializr.com/ 등을 통해

제공 환경에 따라 쉽게 설치 구축 가능

• http://cornerstone.sktelecom.com/ 에서도 활용

Page 71: CG&I web tech_workshop 28 June 2013

22

43

CoreChain

• CoreChain4.0은 크게 Framework와 UI 버전으로 구성(HTML5 기반 웹페이지 모델링)

• MIT, GPL 라이선스 기반(Open Source)- 순수 국내 기술

• Framework

•One Object, Method Channing, Client Computing, Component 개념 적용

•One Object는 최상위 오브젝트로 메소드와 속성을 지정하기 위해 오브젝트를 생성하지 않음

•분산 클라이언트 연산을 통해 서버 자원의 효율적 사용(Calculator, Operator)

•CoreChain은 컴포넌트 개념으로 확장(사용자 개발 컴포넌트를 CoreChain에 등록해서 사용 가능)

• UI(Canvas)

•기본 Type UI 지원(Text, Number, FildSet, Label…)

•Combo, Form, Ground 기능 UI 지원

•Bar, Line, Circle Chart, Gide와 같은 Enterprise UI 지원

• API

•Data Format은 최종 Meta Data으로 설정

•클라이언트는 JSON 형태로만 작성하면 다양한 Format으로 변환

•지원 Format(Array, CSV, JSON, XML, HTML) 지원

44

Hybrid 기술 활용

• 모바일 서비스 개발을 위한 전용 어플리케이션 프레임워크에 활용

• JS 코드를 통해 Web-to-Native 기술이 보편적으로 보급되어 활용되고 있음

Javascript tools

App factories

Web-to-native Runtimes

Source translators

Page 72: CG&I web tech_workshop 28 June 2013

23

45

Hybrid 기술 활용

• Web-to-Native Wrappers(JavaScript을 통해 플랫폼의 Native API를 호출하는 방식)

• Runtime은 기본적인 실행 환경을 플랫폼에 설치한 후 구동하는 방식으로 제공

Vendor (Tool) Technology approach Authoring language Deploy. format

Adobe (Flex) SDK addition to AIR

Runtime addition to AIR MXML Native, Hybrid

Appcelerator (Titanium)

Runtime HTML5, CSS, JavaScript Native apps

PhoneGap (Nitobi- Adobe)

Web-to-native app wrapper HTML5, CSS, JavaScript Hybrid

RhoMobile (Rhoelements)

Runtime HTML5, JavaScript, Ruby Native

IBM (Worklight) Runtime, Web-to-native app

wrapper (PhoneGap) HTML5, CSS, JavaScript

Web apps, Hybrid, Native

Ansca Mobile(Corona) Runtime Lua Native(Game)

RunRev (LiveCode) Runtime WYSIWYG, LiveCode

(natural-like language) Native

appspresso Runtime, Web-to-native app

wrapper (PhoneGap) HTML5, CSS, JavaScript Web apps, Native

AppMobi Runtime (Mobius) Web-to native

app wrapper(PhoneGap) HTML5, CSS, JavaScript Web apps, Hybrid

46

• PhoneGap

HTML+JS로 제작된 웹 앱을 담는 컨테이너

HTML5 + CSS3 + JS 로 개발

다양한 모바일 플랫폼 네이티브 앱으로 변환

기존에 웹 앱에서 불가능했던 디바이스 기능을 JS로 접근가능

• 가속도계, 카메라, 주소록, 파일, 네트워크 등 지원

• 스토리지, 푸시, GPS 등 사용 가능

최근 PhoneGap Build 시스템 구축

• 클라우드 컨셉을 SW개발에 적용

PhoneGap 소개

• PhoneGap은 크로스 플랫폼 모바일 전용 어플리케이션 프레임워크

• 폭넓은 사용자 층을 기반으로 최근 클라우드형 빌드 시스템 제공

Page 73: CG&I web tech_workshop 28 June 2013

24

47

• 웹 기술을 이용한 모바일/데스크탑 앱 개발 가능

• 4,000개 이상의 iOS, Android 앱 릴리즈, 2011년 10,000개 이상의 앱 런칭 예상

• Main Features

Web-based, cross-compilation tool

Mac, Windows, and Linux support

• 클라우드 기반 빌드 환경 제공

• 최근 개발 툴 업체 Aptana 인수 후 전용 개발 도구 발표

Appcelerator Titanium

<Titanium으로 개발된 Wunderlist>

+

48

Worklight

• 엔터프라이즈를 위한 모바일 통합 솔루션 제공

• IBM에 인수되어 Worklight Studio, Worklight Server, Device Runtime Component 및 Worklight Console 지원

• Main Features

네이티브 코드 또는 PhoneGap 브릿지를 사용하여 디바이스 API에 액세스

기업 환경을 고려한 보안(MDM, 암호화) 지원

Sencha Touch, dojox.mobile, jQueryMobile support

• IBM의 서버 플랫폼과 연동하는 운영 환경 제공

• 디바이스 소프트웨어 개발 키트 내에서 개발, 테스트 및 디버깅 툴에 연결

• API 연결 및 인증

• 로컬 암호화, 오프라인 인증 및 원격 비활성화

• 런타임 스킨, 사용자 인터페이스 분리 및 HTML5 호환성

• 하이브리드 애플리케이션 프레임워크, 액세스 디바이스 API 및 푸시 기반

(Push-based) 등록

• 내장된 보고서 및 이벤트 기반의 사용자 정의 보고서

• 애플리케이션 웹 자원 및 HTML5 캐싱 업데이트

Page 74: CG&I web tech_workshop 28 June 2013

25

49

IV. 최신 JAVASCRIPT 적용 기술 사례

50

Node.js

• 서버 V8 위에서 동작하는 이벤트 처리 I/O 프레임워크

• 확장성 있는 네트워크 프로그램 개발을 위해 고안

• Node.js(http://nodejs.org/)

– Node.js는 실질적으로 서버사이드 자바스크립트 실행환경과

라이브러리로 구성됨

– C++ Addon with Node.js

• V8 엔진도 C++ 로 작성된 라이브러리로 자바스크립트의 오브젝트를

만들거나 함수 호출등의 인터페이스 개발

• Node의 소스 트리 중 deps/v8/include/v8.h를 참고

– 모든 Network I/O 는 NonBlocking , File I/O 는

Asynchronous

– Thread 방식에 비해 뛰어난 성능, 다양한 모듈 개발 중

– HTTPd , FTPd , IMAP, WebDAV 등 다양한 서버 프로토콜

지원(기 개발 지원)

– Node.js는 일부 CommonJS 명세를 구현하고 있으며, 쌍방향

테스트를 위해 Debug 환경을 포함

설치하기 : http://blog.doortts.com/209 http://www.youtube.com/watch?v=jo_B4LTHi3I

C,C++

JavaScript

Page 75: CG&I web tech_workshop 28 June 2013

26

51

HTML5 Canvas 기반 Chart, Grid JS Library

• Rgraph : 그래프 및 차트에 이용되는 데이터를 스크립트를 통해 RGraph 객체로 정의

• flot : JQuery 기반으로 데이터를 자동으로 분석해서 차트로 변환(MIT License)

• ZingChart : 유료(도메인), JSON 형태의 데이터를 분석해서 차트로 변환(갤러리)

http://www.rgraph.net/ http://code.google.com/p/flot/

http://www.zingchart.com/

- Mozilla Firefox 3.0+ - Google Chrome 1+ - Apple Safari 3+ - Opera 9.5+ - Microsoft Internet Explorer 8+ (see note)

Rgraph flot ZingChart

52

3D Library

• 3D화면을 캔버스에서 WebGL이나 SVG를 사용하여 랜더링 할 수 있도록 지원

• Three.js, Sprite3D.js, Canvas 3D JS Libary (C3이) 등을 주로 사용

Page 76: CG&I web tech_workshop 28 June 2013

27

53

Thank you

Page 77: CG&I web tech_workshop 28 June 2013

Web Graphics I : Canvas Element

2013.06.28

이인균

[email protected]

HTML5 Canvas?

• The HTML5 Canvas is an Immediate Mode bit-mapped area of the screen that can be manipulated with JavaScript and CSS.

• The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).

• The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics.

• Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.

2

Page 78: CG&I web tech_workshop 28 June 2013

Flash vs Canvas

• Finished Essential guide To Flash Games in March 2010.

• Steve Jobs refused Flash on the iOS just days later.

• Easy Tools: a web browser, text editor and JavaScript was all that was required.

• The HTML5 Canvas allowed for a bitmapped graphics, much Flash’s bitmapped canvas.

• Our specific Type Of Game Development translates well (tile sheets, bitmaps)

3

Retained mode vs Immediate

Fig1. Retained Mode

Fig2. Immediate Mode

4

Page 79: CG&I web tech_workshop 28 June 2013

HTML5 Canvas Support

Source : http://caniuse.com

5

References

• Web sites

http://diveintohtml5.org/canvas.html

https://developer.mozilla.org/en/Canvas_tutorial

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html

http://www.html5canvastutorials.com

http://www.w3schools.com

• Books

HTML5: Guidelines for Web Developers by Klaus Förster and Bernd Öggl

HTML5 Canvas by Steve Fulton, Jeff Fulton

6

Page 80: CG&I web tech_workshop 28 June 2013

What Can The Canvas Be Used for?

• Nearly anything that Flash notorious for:

Banner Ads

Animated Landing Pages

Web Games

Video

7

HTML5 Canvas properties & methods

• width

• height

• id

• getContext()

• toDataUrl()

<canvas id=“MyFirstCanvas” width=“600” heght=“200”></canvas>

8

Page 81: CG&I web tech_workshop 28 June 2013

Colors, Styles, and Shadows

Property Description

fillStyle Sets or returns the color, gradient, or pattern used to fill the drawing

strokeStyle Sets or returns the color, gradient, or pattern used for strokes

shadowColor Sets or returns the color to use for shadows

shadowBlur Sets or returns the blur level for shadows

shadowOffsetX Sets or returns the horizontal distance of the shadow from the shape

shadowOffsetY Sets or returns the vertical distance of the shadow from the shape

Method Description

createLinearGradient() Creates a linear gradient (to use on canvas content)

createPattern() Repeats a specified element in the specified direction

createRadialGradient() Creates a radial/circular gradient (to use on canvas content)

addColorStop() Specifies the colors and stop positions in a gradient object

9

Rectangles

Method Description

rect() Creates a rectangle

fillRect() Draws a "filled" rectangle

strokeRect() Draws a rectangle (no fill)

clearRect() Clears the specified pixels within a given rectangle

10

Page 82: CG&I web tech_workshop 28 June 2013

Line Styles

Property Description

lineCap Sets or returns the style of the end caps for a line

lineJoin Sets or returns the type of corner created, when two lines meet

lineWidth Sets or returns the current line width

miterLimit Sets or returns the maximum miter length

11

Paths

Method Description

fill() Fills the current drawing (path)

stroke() Actually draws the path you have defined

beginPath() Begins a path, or resets the current path

moveTo() Moves the path to the specified point in the canvas, without creating a line

closePath() Creates a path from the current point back to the starting point

lineTo() Adds a new point and creates a line from that point to the last specified point in the canvas

clip() Clips a region of any shape and size from the original canvas

quadraticCurveTo() Creates a quadratic Bézier curve

bezierCurveTo() Creates a cubic Bézier curve

arc() Creates an arc/curve (used to create circles, or parts of circles)

arcTo() Creates an arc/curve between two tangents

isPointInPath() Returns true if the specified point is in the current path, otherwise false

12

Page 83: CG&I web tech_workshop 28 June 2013

Transformations

Method Description

scale() Scales the current drawing bigger or smaller

rotate() Rotates the current drawing

translate() Remaps the (0,0) position on the canvas

transform() Replaces the current transformation matrix for the drawing

setTransform() Resets the current transform to the identity matrix. Then runs transform()

13

Text

Property Description

font Sets or returns the current font properties for text content

textAlign Sets or returns the current alignment for text content

textBaseline Sets or returns the current text baseline used when drawing text

Method Description

fillText() Draws "filled" text on the canvas

strokeText() Draws text on the canvas (no fill)

measureText() Returns an object that contains the width of the specified text

14

Page 84: CG&I web tech_workshop 28 June 2013

Images

Method Description

drawImage() Draws an image, canvas, or video onto the canvas

Property Description

width Returns the width of an ImageData object

height Returns the height of an ImageData object

data Returns an object that contains image data of a specified ImageData object

Method Description

createImageData() Creates a new, blank ImageData object

getImageData() Returns an ImageData object that copies the pixel data for the specified rectangle on a canvas

putImageData() Puts the image data (from a specified ImageData object) back onto the canvas

15

Compositing & Others

Property Description

globalAlpha Sets or returns the current alpha or transparency value of the drawing

globalCompositeOperation Sets or returns how a new image are drawn onto an existing image

Method Description

save() Saves the state of the current context

restore() Returns previously saved path state and attributes

createEvent()

getContext()

toDataURL()

16

Page 85: CG&I web tech_workshop 28 June 2013

Ex1 - Two overlapped rectanges

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

context.fillStyle = 'red';

context.fillRect(0,0,800,600);

context.fillStyle = 'rgba(255,255,0,0.5)';

context.fillRect(400,200,800,600);

</script>

17

Ex2 - Bar chart with ten horizontal bars

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

context.fillStyle = 'silver';

context.strokeStyle = 'rgba(0,0,0,0.5)';

context.shadowOffsetX = 2.0;

context.shadowOffsetY = 2.0;

context.shadowColor = "rgba(50%,50%,50%,0.75)";

context.shadowBlur = 2.0;

var drawBars = function(bars) {

context.clearRect(0,0,canvas.width,canvas.height);

for (var i=0; i<bars; i++) {

………………

}

window.figures.addIcon(context,0,'mouse.png');

};

drawBars(10);

context.canvas.onclick = function() {

drawBars(10);

};

</script>

18

Page 86: CG&I web tech_workshop 28 June 2013

Ex3 - The Canvas coordinate system

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

// center graphic

context.setTransform(1,0,0,1,100,100);

// draw grid 1000x600

context.strokeStyle = 'rgba(0,0,0,0.5)';

context.lineWidth = 0.5;

for (var xOff=0; xOff<=1000; xOff+=100) {

// vertical lines

context.beginPath();

context.moveTo(xOff,0);

context.lineTo(xOff,600);

context.stroke();

}

for (var yOff=0; yOff<=600; yOff+=100) {

// horizontal lines

context.beginPath();

context.moveTo(0,yOff);

context.lineTo(1000,yOff);

context.stroke();

}

………………………………………………..

</script> 19

Ex4 - Linear gradient with four colors

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

// center

context.setTransform(1,0,0,1,100,0);

// draw linear gradient

var grad = context.createLinearGradient(

0,450,1000,450

);

grad.addColorStop(0.0,'red');

grad.addColorStop(0.5,'yellow');

grad.addColorStop(0.7,'orange');

grad.addColorStop(1.0,'purple');

context.fillStyle = grad;

context.fillRect(0,450,1000,300);

context.strokeRect(0,450,1000,300);

…………………….

</script>

20

Page 87: CG&I web tech_workshop 28 June 2013

Ex5 - Linear gradient with four colors

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

…………………….

context.setTransform(1,0,0,1,770,0);

var radGrad = context.createRadialGradient(

260,320,40,200,400,200

);

radGrad.addColorStop(0.0, 'yellow');

radGrad.addColorStop(0.9, 'orange');

radGrad.addColorStop(1.0, 'rgba(0,0,0,0)');

context.fillStyle = radGrad;

context.fillRect(0,200,400,400);

…………………….

</script>

21

Ex6 - The letter A as a path

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

…………………….

// mark x/y direction and 0/0

context.beginPath();

context.strokeStyle = 'rgba(0,0,0,1)';

context.lineWidth = 1;

context.beginPath();

context.moveTo(0,0);

context.lineTo(1200,0);

context.moveTo(0,0);

context.lineTo(0,800);

context.stroke();

…………………….

</script>

22

Page 88: CG&I web tech_workshop 28 June 2013

Ex7 - The letter A as a path

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

…………………….

var lineTo = function() {

…………………….

// geometry

context.save();

context.beginPath();

context.moveTo(20,130);

context.lineTo(130,20);

context.strokeStyle = colors.path;

context.stroke();

context.restore();

};

…………………….

</script>

23

Ex8 - The path method “quadraticCurveTo()”

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

…………………….

// geometry

context.save();

context.beginPath();

context.moveTo(20,130);

context.quadraticCurveTo(20,20,130,20);

context.strokeStyle = colors.path;

context.stroke();

context.restore();

…………………….

</script>

24

Page 89: CG&I web tech_workshop 28 June 2013

Ex9 - The path method “bezierCurveTo()”

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

…………………….

// geometry

context.save();

context.beginPath();

context.moveTo(20,130);

context.bezierCurveTo(100,130,40,20,130,20);

context.strokeStyle = colors.path;

context.stroke();

context.restore();

…………………….

</script>

25

Ex10 - The path method “arcTo()”

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

…………………….

// geometry

context.save();

context.beginPath();

context.moveTo(20,130);

context.arcTo(20,20,130,20,40);

context.strokeStyle = colors.path;

context.stroke();

context.restore();

…………………….

</script>

26

Page 90: CG&I web tech_workshop 28 June 2013

Ex11 - Four different rounded rectangles

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

var roundedRect = function(x,y,w,h,r) {

context.beginPath();

context.moveTo(x,y+r);

context.arcTo(x,y,x+w,y,r);

context.arcTo(x+w,y,x+w,y+h,r);

context.arcTo(x+w,y+h,x,y+h,r);

context.arcTo(x,y+h,x,y,r);

context.closePath();

context.stroke();

};

roundedRect(100,100,700,500,60);

roundedRect(900,150,160,160,80);

roundedRect(700,400,400,300,40);

roundedRect(150,650,400,80,10);

</script>

27

Ex12 - The path method “arc()”

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

…………………….

context.save();

context.strokeStyle = colors.pathLegend;

context.beginPath();

context.moveTo(75,75);

context.lineTo(130,75);

context.moveTo(75,75);

context.arc(75,75,55,

(-70.0*(Math.PI/180.0)),

(155.0*(Math.PI/180.0)),0);

context.closePath();

context.stroke();

context.restore();

…………………….

</script>

28

Page 91: CG&I web tech_workshop 28 June 2013

Ex13 - Circles and sectors

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

var circle = function(cx,cy,r) {

context.moveTo(cx+r,cy);

context.arc(cx,cy,r,0,Math.PI*2.0,0);

};

var sector = function(cx,cy,r,startAngle,endAngle,anticlockwise) {

context.moveTo(cx,cy);

context.arc(

cx,cy,r,

startAngle*(Math.PI/180.0),

endAngle*(Math.PI/180.0),

anticlockwise

);

context.closePath();

}

……………………………..

</script>

29

Ex14 - The path method “rect()”

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

…………………….

// geometry

context.save();

context.beginPath();

context.rect(30,30,100,90);

context.strokeStyle = colors.path;

context.stroke();

context.restore();

…………………….

</script>

30

Page 92: CG&I web tech_workshop 28 June 2013

Ex15 - Attributes for determining line styles

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

…………………….

// thick line

context.lineWidth = 20.0;

// join style

context.beginPath();

context.lineJoin = 'bevel';

context.lineJoin = 'round';

context.lineJoin = 'miter';

context.moveTo(20,130);

context.lineTo(50,50);

context.lineTo(80,130);

context.stroke();

…………………….

// cap style

context.beginPath();

context.lineCap = 'butt';

context.lineCap = 'round';

context.lineCap = 'square';

context.moveTo(50,130);

context.lineTo(50,50);

context.stroke();

…………………….

</script> 31

Ex16 - The non-zero fill rule for paths

// circle with anticlockwise

var circle = function(cx,cy,r,anticlockwise) {

context.moveTo(cx+r,cy);

context.arc(cx,cy,r,0,Math.PI*2.0,anticlockwise);

};

…………………………………

circle(300,400,240,0);

circle(300,400,120,0);

circle(900,400,240,0);

circle(900,400,120,1);

32

Page 93: CG&I web tech_workshop 28 June 2013

Ex17 - Font formatting with the “font” attribute var fonts = [

'oblique 1.3em monospace',

'bolder 110% serif',

'x-large "New Century Schoolbook"',

'bold italic 16pt Palatino',

'normal small-caps 120% Helvetica',

'normal 130% Scriptina' // buggy, see: http://stackoverflow.com/questions/2756575/drawing-text-to- canvas-with-font-face-does-not-work-at-the-first-time

];

……………………..

for (var i=0; i<fonts.length; i++) {

context.save();

context.font = '11px monospace';

context.fillStyle = '#666';

context.fillText("context.font='"+

fonts[i]+"'",0,yOff);

context.font = fonts[i];

context.fillStyle = '#000';

context.fillText(t,0,yOff);

}

}

33

Ex18 - Horizontal anchor points with “textAlign”

context.textAlign = [

left | right | center | *start | end

]

34

Page 94: CG&I web tech_workshop 28 June 2013

Ex19 - Vertical anchor points with “textBaseline”

context.textBaseline = [

top | middle | *alphabetic | bottom | hanging | ideographic

]

35

Ex20 - “fillText()”, “strokeText()”, and “measureText()” <script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

var t = 'Lorem ipsum dolor sit amet.';

context.translate(180,-20);

context.font = '28px monospace';

context.fillStyle = '#666';

context.fillText('context.fillText(text,0,0)',0,130);

context.fillText('context.strokeText(text,0,0)',0,330);

context.fillText('context.fillText(text,0,0,580)',0,530);

………………………………………………

var w = context.measureText(t).width;

window.figures.drawArrow(context,0,

680,-90);

window.figures.drawArrow(context,580,

680,-90,undefined,undefined,'#000',true);

window.figures.drawArrow(context,0+w,

680,-90);

………………………………………………

</script>

36

Page 95: CG&I web tech_workshop 28 June 2013

Ex21 - Position parameters of the “drawImage()” method

context.drawImage(image, dx, dy);

context.drawImage(image, dx, dy, dw, dh);

context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);

37

Ex22 - The source image of all “drawImage()” examples <script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

var arrow = function(x,y,deg) {

window.figures.drawArrow(context,x,y,deg,undefined,undefined,'#666');

};

var image = new Image();

image.src = 'images/yosemite.jpg';

image.onload = function() {

// scale down a bit

var s = 0.8;

context.translate(120,80)

context.scale(s,s);

window.figures.useShadow(context,true);

context.drawImage(image,0,0,1200,800);

window.figures.useShadow(context,false);

};

</script>

38

Page 96: CG&I web tech_workshop 28 June 2013

Ex27 - The “ImageData” object

var w = 200;

var h = 200;

var colorIdx = 0;

var colors = [

[ 0, 0,128,255], // navy

[ 0,128,128,255], // teal

[ 0,255, 0,255], // lime

[255,255, 0,255] // yellow

];

context.fillStyle = ‘navy’;

context.fillRect(0, 0, 1, 1);

context.fillStyle = ‘teal’;

context.fillRect(1, 0, 1, 1);

context.fillStyle = ‘lime’;

context.fillRect(0, 1, 1, 1);

context.fillStyle = ‘yellow’;

context.fillRect(1, 1, 1, 1);

ImageData = context.getImageData(

0, 0, canvas.width, canvas.height);

39

Ex28 - Modifying colors in the “CanvasPixelArray”

context.putImageData(

ImageData, dx, dy, [ dirtyX, dirtyY, dirtyWidth, dirtyHeight ]

)

40

Page 97: CG&I web tech_workshop 28 June 2013

Ex29 - Color manipulation with “getImageData()” and “putImageData()” var image = new Image();

image.src = ‘images/yosemite.jpg’;

image.onload = func() {

context.drawImage(image, 0, 0, 360, 240);

var modified = context.createImageData(360, 240);

for (var i=0; i<imagedata.data.length; i+=4) {

var rgba = grayLuminosity(

imagedata.data[i+0];

imagedata.data[i+1];

imagedata.data[i+2];

imagedata.data[i+3];

);

modified.data[i+0] = rgba[0];

modified.data[i+1] = rgba[1];

modified.data[i+2] = rgba[2];

modified.data[i+3] = rgba[3];

}

context.putImageData(modified, 0, 0);

};

41

Ex30 - Values of the “globalCompositeOperation” attribute context.save();

context.translate(x+150,y);

window.figures.useShadow(context,true);

context.fillStyle = '#000';

context.font = '30px sans-serif';

context.textAlign = 'center';

context.textBaseline = 'bottom';

context.globalCompositeOperation = 'source-over';

context.fillText(operations[i],0,200);

context.font = 'italic 18px sans-serif';

//context.fillStyle = '#666';

context.fillText(duftnames[i],0,225);

context.restore();

42

Page 98: CG&I web tech_workshop 28 June 2013

Ex33 - Checkered pattern in eight color combinations var cvs = document.createElement("CANVAS");

cvs.width = 20;

cvs.height = 20;

var ctx = cvs.getContext('2d');

// define fill pattern

ctx.fillStyle = colors[(i*2)+0];

ctx.fillRect(0,0,10,10);

ctx.fillStyle = colors[(i*2)+1];

ctx.fillRect(10,0,10,10);

ctx.fillStyle = colors[(i*2)+1];

ctx.fillRect(0,10,10,10);

ctx.fillStyle = colors[(i*2)+0];

ctx.fillRect(10,10,10,10);

context.fillStyle = context.createPattern(cvs,'repeat');

context.fillRect(x,y,220,220);

43

Ex34 - Pattern using images as a source

var extents = [

{ x:20, y:50, width:120,height:550 },

{ x:100,y:170,width:520,height:350 },

{ x:320,y:250,width:150,height:500 },

{ x:440,y:600,width:425,height:180 },

{ x:600,y:280,width:350,height:370 },

{ x:760,y:225,width:410,height:160 },

{ x:900,y:520,width:270,height:240 },

{ x:970,y:420,width:50,height:50 }

];

for (var i=0; i<extents.length; i++) {

var d = extents[i]; // short-cut

context.fillRect(d.x,d.y,d.width,d.height);

context.strokeRect(d.x,d.y,d.width,d.height);

}

44

Page 99: CG&I web tech_workshop 28 June 2013

Ex35 - The basic transformations “scale()”, “rotate()”, and “translate()”

context.scale(x, y);

context.rotate(angle);

context.translate(x, y);

45

Ex36 - Rotate, scale and move

<script>

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

var image = new Image();

image.src = 'images/yosemite.jpg';

image.onload = function() {

var rotate = 15;

var scaleStart = 0.0;

var scaleEnd = 4.0;

var scaleInc = (scaleEnd-scaleStart)/(360/rotate);

var s = scaleStart;

for (var i=0; i<=360; i+=rotate) {

s += scaleInc;

context.translate(540,260);

context.scale(s,s);

context.rotate(i*-1* Math.PI / 180);

context.drawImage(image,0,0,120,80);

context.setTransform(1,0,0,1,0,0);

}

</script>

46

Page 100: CG&I web tech_workshop 28 June 2013

Ex37 - Photo collage with mirror effect in pseudo-3D context.transform(m11, m12, m21, m22, dx, dy);

context.setTransform(m11, m12, m21, m22, dx, dy);

Parameter Description

a Scales the drawing horizontally

b Skew the the drawing horizontally

c Skew the the drawing vertically

d Scales the drawing vertically

e Moves the the drawing horizontally

f Moves the the drawing vertically

47

Thank you

48

Page 101: CG&I web tech_workshop 28 June 2013

1

Web Graphics 2 : SVG의 활용

28 June 2013

윤지영 [email protected]

SVG 데모

• Tiger & 좌표

2

Page 102: CG&I web tech_workshop 28 June 2013

2

SVG 개요

• SVG

Scalable Vector Graphics

W3C(World Wide Web Consortium) 표준

2차원 벡터 그래픽스

XML 기반

상호작용

애니메이션

멀티미디어

자바스크립트

3

SVG 장점

• 순수 XML 파일

텍스트 에디터 등으로 편집 가능

• 작은 파일 크기

압축 기술 적용 가능

• 고품질, 고해상도 출력 가능

확대 축소에 품질 저하 없음

• 개방형 표준

CSS, DOM 등 표준 기술 준수

• 다양한 그래픽 기술 포함

Path, Gradient, Filter 등

• HTML5에서 inline SVG 지원

4

Page 103: CG&I web tech_workshop 28 June 2013

3

SVG 활용 분석

• Google 검색 링크 분석

5

Query 2005 Current

HTML 1,610,000,000 25,270,000,000

PHP 454,000,000 17,220,000,000

Java 150,000,000 833,000,000

Perl 51,600,000 105,000,000

JavaScript 49,900,000 1,960,000,000

C++ 28,900,000 179,000,000

Fortran 5,350,000 12,700,000

SVG 3,750,000 131,000,000

SVG 히스토리

6

1998 4 Sep 2001

14 Jan 2003

22 Dec 2008

16 Aug 2011

Aug 2014

Start development SVG 1.0 SVG 1.1

Defines

SVG Tiny SVG Basic

SVG Tiny 1.2

SVG 1.1 Second Edition

SVG 2.0

Page 104: CG&I web tech_workshop 28 June 2013

4

웹 브라우저 지원

7

SVG의 W3C 표준

8

SVG

CSS Cascading Style Sheet

DOM Document Object Model

SMIL Synchronized Multimedia

Integration Language

Page 105: CG&I web tech_workshop 28 June 2013

5

저작 도구(1/4)

• 텍스트 에디터

• Adobe Illustrator

9

저장

편집

저작 도구(2/4)

• 벡터 매직

Bitmap 이미지를 자동으로 벡터 그래픽으로 변환

http://vectormagic.com/home

10

Page 106: CG&I web tech_workshop 28 June 2013

6

저작 도구(3/4)

• Online Convert

웹 상에서 이미지를 SVG로 변환

http://image.online-convert.com/convert-to-svg

11

저작 도구(4/4)

• Google SVG-edit

웹 브라우저 상에서 SVG 에디트 도구 제공

http://svg-edit.googlecode.com

12

Page 107: CG&I web tech_workshop 28 June 2013

7

SVG 사용

• 간단 예제

13

?xml version="1.0" standalone="no"? !DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" svg xmlns="http://www.w3.org/2000/svg" version="1.1" circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" / /svg

SVG 구문(1/2)

14

Element

Attribute 1 Attribute 2 Attribute …

Property 1 Property 2 Property …

Container Element 1

Container Element …

Page 108: CG&I web tech_workshop 28 June 2013

8

SVG 구문(2/2)

• SVG Element 구문

15

SVG 좌표 및 변환

• 좌표 시스템

Left/Top 기준

• 3x3 변환 행렬

‘transform’ attribute

• matrix, translate, rotate, scale, skewX, skew

16

Page 109: CG&I web tech_workshop 28 June 2013

9

SVG Element 카테고리(1/2)

Category Element List

Animation Animate, animateColor, animateMotion, animateTransform, set

Basic Shape circle, ellipse, line, polygon, polyline, rect

Container A, defs, glyph, g, marker, mask, missing-glyph, pattern, svg, switch, symbol

Descriptive desc, metadata, title

Filter Primitive

feBlend, feColorMatrix, feComponentTransfer, feComposite, feConvolveMatrix, feDiffuseLighting, feDisplacementMap, feFlood, feGaussianBlur, feImage, feMerge, feMorphology, feOffset, feSpecularLighting, feTile, feTurbulence

Gradient linearGradient, radialGradient

17

SVG Element 카테고리(2/2)

18

Category Element List

Graphics circle, ellipse, image, line, path, polygon, polyline, rect, text, use

Light Source feDistantLight, fePointLight, feSpotLight

Shape circle, ellipse, line, path, polygon, polyline, rect

Text Content altGlyph, textPath, text, tref, tspan

Text Content Child altGlyph, textPath, tref, tspan

Uncategorized

altGlyphDef, altGlyphItem, clipPath, color-profile, cursor, filter, font, font-face, font-face-format, font-face-name, font-face-src, font-face-uri, foreignObject, glyph, glyphRef, hkern, mpath, script, stop, style, view, vkern

Page 110: CG&I web tech_workshop 28 June 2013

10

SVG Shapes

• Element 종류

line, rect, circle, ellipse, polygon, polyline

• Circle Element 예제

19

circle cx="80" cy="50" r="40"/ circle cx="80" cy="110" r="40" fill="red"/ circle cx="80" cy="170" r="40" fill="yellow" stroke="blue" / circle cx="80" cy="160" r="20" fill="red" stroke="black" stroke-width="10"/ circle cx="140" cy="110" r="60" fill="none" stroke="#579" stroke-width="30" stroke-dasharray="3,5,8,13"

SVG Path(1/2)

• Path Element 예제

20

path d="M100,400Q200,300 300,400T500,400“ stroke-width="4" fill="blue" stroke="green"/

Page 111: CG&I web tech_workshop 28 June 2013

11

SVG Path(2/2)

• ‘d’ Attribute 사용

21

명령 내용 기호 매개변수

moveto (no drawing) M m (x y)+

closepath (끝점-시작점 사이 line) Z z

lineto

General Line L l (x y)+

Horizontal Line H h x+

Vertical Lline V v y+

curveto

cubic Bezier C c (x1 y1 x2 y2 x y)+

연속 cubic Bezier S s (x2 y2 x y)+

Quadratic Bezier Q q (x1 y1 x y)+

연속 Quadratic Bezier T t (x y)+

SVG Text

• Element 종류

text, tspan, tref, textPath

• textPath Element 예제

22

defs path id="path1" d="M75,20 a1,1 0 0,0 100,0" / /defs text x="10" y="100" style="fill:red;" textPath xlink:href="#path1"I love SVG I love SVG/textPath /text

Page 112: CG&I web tech_workshop 28 June 2013

12

SVG Gradient

• Element 종류

linearGradient, radialGradient, stop

• radialGradient Element 예제

23

defs radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%" stop offset="0%" stop-color="rgb(255,255,255)" stop-opacity="1" / stop offset="100%" stop-color="rgb(0,0,255)" stop-opacity="1" / /radialGradient /defs ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" /

SVG Animation(1/3)

• Element 종류

set, animate, animateColor, animateMotion, animateTransform

• SMIL 2.0 기반

• animateMotion Element 예제

24

path id=“MyPath" d="M0 0c30 100 500 -100 530 0"/ circle x="20" y="320" r="10" fill="red" animateMotion dur="3s" begin=“0s“ repeatCount="indefinite” mpath xlink:href="#MyPath"/ /animateMotion /circle

Page 113: CG&I web tech_workshop 28 June 2013

13

SVG Animation(2/3)

• SVG 애니메이션과 데모

25

SVG Animation(3/3)

• 지원 웹 브라우저

26

Page 114: CG&I web tech_workshop 28 June 2013

14

SVG Filter(1/5)

• SVG Filter 개요

각종 필터 효과를 SVG 그래픽에 적용

W3C 2006년~2010년 표준 제안

• Svg Open 2010에서 소개

• Filter 정의

‘filter’ Element

Filter Primitive와 함께 사용

27

SVG Filter(2/5)

• Filter Primitives

28

Filter

feDistantLight fePointLight feSpotLight feBlend feColorMatrix

feComponent Transfer

feComposite feConvolve

Matrix feDiffuse Lighting

feDisplacement Map

feFlood feGaussianBlur feImage feMerge feMorphology

feOffset feSpecular Lighting

feTile feTurbulence

Page 115: CG&I web tech_workshop 28 June 2013

15

SVG Filter(3/5)

• Gaussian Blur Filter 예제

29

defs filter id="f1" x="0" y="0" feGaussianBlur in="SourceGraphic" stdDeviation="15" / /filter /defs rect width="90" height="90" stroke="green" stroke-width="3" fill="yellow" filter="url(#f1)" /

SVG Filter(4/5)

• Blending Filter 예제

30

defs filter id='MyFilter' filterUnits='userSpaceOnUse' x='0' y='0' width='200' height='200' feImage xlink:href='#MyImage1' result='pict1'/ feImage xlink:href='#MyImage2' result='pict2'/ feBlend in='pict1' in2='pict2' mode='multiply'/ /filter /defs rect width="90" height="90" stroke="green" stroke-width="3" fill="yellow" filter="url(#f1)" /

Page 116: CG&I web tech_workshop 28 June 2013

16

SVG Filter(5/5)

• 지원 웹 브라우저

31

E-Book 데모(1/2)

• 동화책 데모

32

Page 117: CG&I web tech_workshop 28 June 2013

17

E-Book 데모(2/2)

• 영화 잡지 데모

33

Lyrics 데모

34

Page 118: CG&I web tech_workshop 28 June 2013

18

Photo Album 데모

35

참고 사이트

• 스펙 사이트

SVG 1.1 Second Edition

• http://www.w3.org/TR/SVG/

Mobile SVG Profiles SVG Tiny and SVG Basic

• http://www.w3.org/TR/SVGMobile/

SVG Tiny 1.2

• http://www.w3.org/TR/SVGTiny12/

SVG Filter

• http://www.w3.org/TR/SVG/finters.html

• 강좌 사이트

W3schools.com - http://www.w3schools.com/svg/svg_intro.asp

36

Page 119: CG&I web tech_workshop 28 June 2013

19

감사합니다

37

Page 120: CG&I web tech_workshop 28 June 2013

6/24/2013

1

WebGL WebGraphics III

백 낙훈 경북대학교, Mobile Graphics Lab.

28 June 2013

차세대 웹 콘텐츠 기술워크샵 KCC 2013

1

Contents • introduction to WebGL

• WebGL shader programming

• current status

• related libraries

• sample implementations

• conclusion

2

Page 121: CG&I web tech_workshop 28 June 2013

6/24/2013

2

Introduction to WebGL

3

그래픽스 출력의 발전 방향 • high-end desktop mobile graphics cross-platform

4

high-end desktop graphics mobile graphics

augmented reality cross-platform graphics

Page 122: CG&I web tech_workshop 28 June 2013

6/24/2013

3

Various platforms for the same code

5

Safari on Mac OS X

Chrome on Windows

Chromium on Linux

Firefox Mobile on Android

Web Programming • HTML5 document DOM Tree output

6

Page 123: CG&I web tech_workshop 28 June 2013

6/24/2013

4

Canvas • canvas tag

7

Drawing Context • in JavaScript

8

Page 124: CG&I web tech_workshop 28 June 2013

6/24/2013

5

Canvas Animation • http://www.blobsallad.se/

9

WebGL 개요 • goal:

- interactive 3D graphics (and 2D)

- within any web browsers

- without the use of plug-ins

• supported web browsers

- Google Chrome

- Mozilla Firefox

- Safari (disabled by default)

- Opera (disabled by default)

10

Page 125: CG&I web tech_workshop 28 June 2013

6/24/2013

6

WebGL history • Year 2006: Canvas 3D experiments at Mozilla

- Vladmir Vukicevic

• Year 2007: Mozilla and Opera implementations

- both works as prototypes

• Year 2009: Khronos Group

- WebGL working group started

- Apple, Google, Mozilla, Opera and others

• Year 2011: WebGL 1.0 released @SIGGRAPH 2011

- cross-platform OpenGL 표준 발의

- Khronos Group 에서 주관

11

WebGL shader programming

12

Page 126: CG&I web tech_workshop 28 June 2013

6/24/2013

7

WebGL concepts • WebGL brings 3D graphics to the HTML5 platform

- Plugin free: never lose a user because they are afraid to

download and install something from the web

- Based on OpenGL ES 2.0: same for desktops, laptops, mobile

devices, etc

- Secure: ensure no out of bounds or uninitialized memory

accesses

• WebGL is an alternative rendering context for the HTML5

Canvas element

• WebGL = Javascript + Shaders

- Shaders - small programs that execute on the GPU - determine

position of each triangle and color of each pixel

13

Programming Model

• The GPU is a stream processor

• Vertex attributes: each point in 3D space has one or more

streams of data associated with it

- Position, surface normal, color, texture coordinate, ...

• These streams of data flow through the vertex and fragment

shaders

• Shaders are small, stateless programs which run on the GPU

with a high degree of parallelism

14

Page 127: CG&I web tech_workshop 28 June 2013

6/24/2013

8

Program Architecture • step 1: prepare TWO shader programs

- shader is a small program

- must be compiled, linked, executed !

• step 2: provide vertices shader executed automatically

15

Real Example • very simple vertex shader: by-pass the input vertex

• simple primitive: draw a triangle

• very simple fragment shader: output red color

16

(-0.5,-0.5) (+0.5,-0.5)

(-0.5,+0.5)

vertex positions

primitive: triangle

fragments output

Page 128: CG&I web tech_workshop 28 June 2013

6/24/2013

9

Vertex Shader Source Code

attribute vec4 vertex;

void main(void) {

gl_Position = vertex;

}

• attribute : later bound to a vertex array !

17

Fragment Shader Source Code

void main(void) {

gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);;

}

18

red color

Page 129: CG&I web tech_workshop 28 June 2013

6/24/2013

10

Source Code <html>

<head>

<title>LAB 01.</title>

<script id="shader-fs" type="x-shader/x-fragment">

void main(void) {

gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);

}

</script>

<script id="shader-vs" type="x-shader/x-vertex">

attribute vec4 vertex;

void main(void) {

gl_Position = vertex;

}

</script>

19

Source Code <script type="text/javascript">

var gl = null;

var viewportWidth = 0;

var viewportHeight = 0;

function initGL(canvas) {

try {

gl = canvas.getContext("webgl");

if (!gl) gl = canvas.getContext("experimental-webgl");

if (gl) {

viewportWidth = canvas.width;

viewportHeight = canvas.height;

}

} catch (e) {

}

if (!gl) {

alert("Could not initialise WebGL, sorry :-(");

}

}

20

Page 130: CG&I web tech_workshop 28 June 2013

6/24/2013

11

Source Code var vs; // vertex shader

var fs; // fragment shader

var prog;

function initProg() {

var script;

// vertex shader

script = document.getElementById("shader-vs");

vs = gl.createShader(gl.VERTEX_SHADER);

gl.shaderSource(vs, script.text);

gl.compileShader(vs);

// fragment shader

script = document.getElementById("shader-fs");

fs = gl.createShader(gl.FRAGMENT_SHADER);

gl.shaderSource(fs, script.text);

gl.compileShader(fs);

21

Source Code // program

prog = gl.createProgram();

gl.attachShader(prog, vs);

gl.attachShader(prog, fs);

gl.linkProgram(prog);

gl.useProgram(prog);

}

22

Page 131: CG&I web tech_workshop 28 June 2013

6/24/2013

12

GL Functions • gl.CreateShader(shaderType);

- type = gl.VERTEX_SHADER, gl.FRAGMENT_SHADER

- returns shader ID number

• gl.ShaderSource(shader, string);

- down load the source code in “string” to the shader

• void glCompileShader(shader);

- compile the source code to get binary file (OBJ)

• there can be several Shaders !

23

GL Functions • gl.CreateProgram(void);

- create a shader program

• gl.AttachShader(program, shader);

- attach the shader to the program

- Warning: you must attach vertex shader and fragment shader

• gl.LinkProgram(program);

- link the shader OBJ’s and make executable

• gl.UseProgram(program);

- install the program to the GPU

• there can be several Shader Programs !

24

Page 132: CG&I web tech_workshop 28 June 2013

6/24/2013

13

Source Code var vertexData = [

// X Y Z W

-0.5, -0.5, 0.0, 1.0,

+0.5, -0.5, 0.0, 1.0,

-0.5, +0.5, 0.0, 1.0,

];

var buffer;

function initGeom() {

// make buffer

buffer = gl.createBuffer();

gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexData),gl.STATIC_DRAW);

// vertex attribute

prog.vertexAttr = gl.getAttribLocation(prog, "vertex");

gl.enableVertexAttribArray(prog.vertexAttr);

gl.vertexAttribPointer(prog.vertexAttr, 4, gl.FLOAT, false, 0, 0);

}

25

(-0.5,-0.5) (+0.5,-0.5)

(-0.5,+0.5)

Vertex Attribute Array • Vertices can have many attributes

- Position

- Color

- Texture Coordinates

- Application data

• A vertex array holds these data

• simple method:

var vertexData = [

// X Y Z W

-0.5, -0.5, 0.0, 1.0,

+0.5, -0.5, 0.0, 1.0,

-0.5, +0.5, 0.0, 1.0,

];

26

Page 133: CG&I web tech_workshop 28 June 2013

6/24/2013

14

Source Code function drawScene() {

// clear

gl.clearColor(0.0, 0.0, 0.0, 1.0);

gl.clear(gl.COLOR_BUFFER_BIT);

// draw

gl.drawArrays(gl.TRIANGLES, 0, 3);

}

function webGLStart() {

var canvas = document.getElementById("canvas");

initGL(canvas);

initProg();

initGeom();

drawScene();

}

27

Source Code </script>

</head>

<body onload="webGLStart();">

LAB 01.<br><br>

<canvas id="canvas" width="500" height="500"></canvas>

</body>

</html>

28

Page 134: CG&I web tech_workshop 28 June 2013

6/24/2013

15

Result • red triangle !

29

Failure on IE…

30

Page 135: CG&I web tech_workshop 28 June 2013

6/24/2013

16

current status

31

WebGL feature check • www.DoesMyBrowserSupportWebGL.com

- result from Chrome (ver 27)

32

Page 136: CG&I web tech_workshop 28 June 2013

6/24/2013

17

WebGL feature check • www.DoesMyBrowserSupportWebGL.com

- result from Internet Explorer 10

33

Another WebGL test • get.webgl.org

34

Page 137: CG&I web tech_workshop 28 June 2013

6/24/2013

18

Security • Validate all input parameters/data in WebGL

- Never leak driver functionality that's not supported in the

WebGL spec

- Out-of-bounds data access detection

- Initialize all allocated objects

• Deal with driver bugs

- Work around where possible

- Browsers actively maintain a blacklist

- Work with driver vendors to fix bugs

- Comprehensive conformance test suite

• Terminate long-running content (accidental or malicious)

35

Security Requirements • GL_ARB_robustness extension

- for OpenGL 3.x and higher

• GL_EXT_robustness extension

- for OpenGL ES

36

Page 138: CG&I web tech_workshop 28 June 2013

6/24/2013

19

Internet Explorer Issues • non-supported web browsers

- Microsoft Internet Explorer (as of version 10)

- will support WebGL from IE 11 (in Windows Blue)

• IEWebGL plugin

- third-party plug-in

- www.iewebgl.com

37

Microsoft Silverlight 5 • Silverlight

- web browser plug-in - GPU acceleration, H.264, MPGE-4 codecs

- high level language that indirectly calls the host system

- indirect calls to DirectX (and XNA)

38

Page 139: CG&I web tech_workshop 28 June 2013

6/24/2013

20

Mobile Browsers • dependent on GPU support…

• Android Browser

- Sony Ericsson Xperia, Samsung Galaxy SII, Galaxy Note 8.0

• BlackBerry Playbook

• Firefox for mobile

• Google Chrome

• Opera Mobile

• Ubuntu Touch

• WebOS

39

CORS: cross-origin resource sharing

• goal : control all WebGL cross-domain textures

• a mechanism that allows Javascript on a web page to

make XMLHttpRequests to another domain, not the

domain the Javascript originated from.

40

Page 140: CG&I web tech_workshop 28 June 2013

6/24/2013

21

• Learning WebGL

- learningwebgl.com

• Mozilla Developer Network

- developer.mozilla.org

Famous WebGL Lectures

41

related libraries

42

Page 141: CG&I web tech_workshop 28 June 2013

6/24/2013

22

WebGL-related Libraries • WebGLU

• GLGE

• C3DL

• Curve3D

• CubicVR

• EnergizeGL

• O3D

• SceneJS

• X3DOM

43

WebGL-related Libraries • Three.js

- a lightweight 3D library for a very low level of complexity

44

Page 142: CG&I web tech_workshop 28 June 2013

6/24/2013

23

WebGL-based Engines • LXEngine http://lx-engine.com/en/main.html

- a JavaScript (game) engine for 3D on the web

45

WebGL-based Engines • CopperLicht

http://www.ambiera.com/copperlicht/index.html

46

Page 143: CG&I web tech_workshop 28 June 2013

6/24/2013

24

JSON • JavaScript Object Notation

• open standard for human-readable data interchange

- derived from the JavaScript scripting language

- now, it is language-independent

• basically, it is general object notation

• example:

47

JSON • JSON C / C++ / Java / Objective C / …

- conversion library 제공

• www.jason.org

48

Page 144: CG&I web tech_workshop 28 June 2013

6/24/2013

25

VRML • Virtual Reality Modeling Language

- since 1994

- managed by Web3D consortium

- succeeded by X3D

- text file format for 3D polygon and animation

- *.wrl and *.wrz extension

- based on SGI Inventor concept - Inventor is more high-level API than OpenGL

- VRML viewer : need additional plug-in - Cosmo Player from SGI

- Cortona Player from Parallel Graphics

49

X3D • eXtensible 3 Dimension

- ISO standard XML-based file format

- for 3D computer graphics

- include all technical features of VRML

- *.x3d and .x3dv extensions

- see www.web3d.org/x3d for more details

• scene-graph system

- higher than WebGL

50

Page 145: CG&I web tech_workshop 28 June 2013

6/24/2013

26

X3DOM • goal:

- live X3D scene through HTML DOM

without plug-ins (so, with WebGL)

• X3DOM: open framework for X3D

- written in JavaScript

- HTML5-based

- implementation result: x3dom.js

- X3D player without any additional programming

51

X3DOM example

52

Page 146: CG&I web tech_workshop 28 June 2013

6/24/2013

27

X3DOM example • http://x3dom.org/x3dom/example/x3dom_shadows.xht

ml

53

WebGL vs. X3D • WebGL is for low-level 3D rendering in the brower

• X3D / VRML is file format for 3D scene graph

• X3DOM on the top of WebGL

- direct rendering of X3D in the browser, without any plug-ins

• positioning

- X3D for fast prototyping

54

Page 147: CG&I web tech_workshop 28 June 2013

6/24/2013

28

sample implementations

55

Google Maps 3D

56

Page 148: CG&I web tech_workshop 28 June 2013

6/24/2013

29

Zygote Body • www.zygotebody.com

57

Aquarium • http://webglsamples.googlecode.com/hg/aquarium/aqu

arium.html

58

Page 150: CG&I web tech_workshop 28 June 2013

6/24/2013

31

Dungeon Fury • http://dungeonfury.playcanvas.com/

- WebGL can be a game framework

61

Pitts Special Demo • http://www.ovoid.org/js/rel/1.1/pittsdemo

- flight simulation demo

62

Page 151: CG&I web tech_workshop 28 June 2013

6/24/2013

32

ChemDoodle.com • chemical drawing and publishing software

- web components: based on WebGL

63

web.chemdoodle.com • http://web.chemdoodle.com/demos/molgrabber-3d

64

Page 152: CG&I web tech_workshop 28 June 2013

6/24/2013

33

Ninja : HTML5 Authoring Tool • http://tetsubo.org/home/ninja/

65

conclusion

66

Page 153: CG&I web tech_workshop 28 June 2013

6/24/2013

34

Conclusion • WebGL is the best shot to bring

3D everywhere

• write once, run everywhere

• cons ?

- network transmission

- even for 3D models and textures

67