2016년 7월 29일 금요일

05day Javascript + HTML5

HTML5

  • Tag추가
    • sementic Tag
    • form 
  • Javascript Library
    • 미디어
      • audio   ←옛날에는 embed +active-x / flash
      • video
      • canvas : 자바스크립트로 그림 그려줌
      • svg : svg라는 xml 태그를 통해서 그림을 그려줌


1. HTML5 수업 세팅

HTML5 Video
브라우저마다 지원하는 동영상 종류가 다름
**스트리밍이나 인터넷 방송은 다른 방식을 사용


2
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- HTML5 video태그 -->
<video width='320' height='240' controls="controls">
    <!-- 브라우저 비디오지원 선택사항 -->
    <source src="./video/movie.mp4" type='video/mp4'>
    <source src="./video/movie.ogg" type='video/ogg'>
    Your browser does not support the video tag.
</video>

</body>
</html>


3
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.button {
    -moz-box-shadow:inset 0px 1px 0px 0px #fce2c1;
    -webkit-box-shadow:inset 0px 1px 0px 0px #fce2c1;
    box-shadow:inset 0px 1px 0px 0px #fce2c1;
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffc477), color-stop(1, #fb9e25) );
    background:-moz-linear-gradient( center top, #ffc477 5%, #fb9e25 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc477', endColorstr='#fb9e25');
    background-color:#ffc477;
    -webkit-border-top-left-radius:20px;
    -moz-border-radius-topleft:20px;
    border-top-left-radius:20px;
    -webkit-border-top-right-radius:20px;
    -moz-border-radius-topright:20px;
    border-top-right-radius:20px;
    -webkit-border-bottom-right-radius:20px;
    -moz-border-radius-bottomright:20px;
    border-bottom-right-radius:20px;
    -webkit-border-bottom-left-radius:20px;
    -moz-border-radius-bottomleft:20px;
    border-bottom-left-radius:20px;
    text-indent:0;
    border:1px solid #eeb44f;
    display:inline-block;
    color:#ffffff;
    font-family:Arial;
    font-size:15px;
    font-weight:bold;
    font-style:normal;
    height:50px;
    line-height:50px;
    width:100px;
    text-decoration:none;
    text-align:center;
    text-shadow:1px 1px 0px #cc9f52;
}
.button:hover {
    background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #fb9e25), color-stop(1, #ffc477) );
    background:-moz-linear-gradient( center top, #fb9e25 5%, #ffc477 100% );
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fb9e25', endColorstr='#ffc477');
    background-color:#fb9e25;
}.button:active {
    position:relative;
    top:1px;
}</style>
/* This button was generated using CSSButtonGenerator.com */
<script type="text/javascript">
    window.onload= function(){
        //자바스크립트로 비디오 제어
        var myVideo = document.getElementById('video');
        
        document.getElementById('btn1').onclick = function(){
            if(myVideo.paused){  //플레이와 일시정지 버튼
                myVideo.play();
            }else{
                myVideo.pause();
            }
        }
    }
</script>
</head>
<body>

<!-- HTML5 video태그 -->
<button id='btn1' class='button'>play/pause</button><br><br>

<video id='video' width='320' height='240'>
    <source src="./video/mov_bbb.mp4" type='video/mp4'>
    <source src="./video/mov_bbb.ogg" type='video/ogg'>
    Your browser does not support the video tag.
</video>

</body>
</html>


4
브라우저마다 지원하는 오디오 방식이 다름


5. SVG-Scalable Vector Graphics
그림크기가 확대되어도 이미지가 깨지지 않음
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- svg 원그리기-->
<svg width='100' height='100'>
    <circle cx='50' cy='50' r='40' fill='yellow' />
</svg>
<!-- 사각형 라운드 그리기 -->
<svg width="400" height="180">
  <rect x="50" y="20" rx="20" ry="20" width="150" height="150" style="fill:red;stroke:black;stroke-width:5;opacity:0.5">
  Sorry, your browser does not support inline SVG.
</svg>
</body>
</html>


6
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- svg 다각형-->
<svg height='210' width='500'>
    <polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:nonzero;"/>
</svg>

</body>
</html>


7
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- svg path 수학도형표시-->
<svg height="400" width="450">
<path id="lineAB" d="M 100 350 l 150 -300" stroke="red" stroke-width="3" fill="none" />
  <path id="lineBC" d="M 250 50 l 150 300" stroke="red" stroke-width="3" fill="none" />
  <path d="M 175 200 l 150 0" stroke="green" stroke-width="3" fill="none" />
  <path d="M 100 350 q 150 -300 300 0" stroke="blue" stroke-width="5" fill="none" />
  <!-- Mark relevant points -->
  <g stroke="black" stroke-width="3" fill="black">
    <circle id="pointA" cx="100" cy="350" r="3" />
    <circle id="pointB" cx="250" cy="50" r="3" />
    <circle id="pointC" cx="400" cy="350" r="3" />
  </g>
  <!-- Label the points -->
  <g font-size="30" font-family="sans-serif" fill="black" stroke="none" text-anchor="middle">
    <text x="100" y="350" dx="-30">A</text>
    <text x="250" y="50" dy="-10">B</text>
    <text x="400" y="350" dx="30">C</text>
  </g>
  Sorry, your browser does not support inline SVG.
</svg>

</body>
</html>


svg로 차트를 그림 --http://www.highcharts.com/ 무료 https://d3js.org/
8. canvas
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #canvas { border: 1px solid black; }
</style>
<script type="text/javascript">
    window.onload = function(){
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(10,10,150,75);
    }
</script>
</head>
<body>
<!-- canvas 그림그리기 javascript 이용-->
<canvas id='canvas' width='500' height='500'></canvas>

</body>
</html>


9
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #canvas { border:1px solid #d3d3d3; }
</style>
<script type="text/javascript">
    window.onload = function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        //canvas에 글씨 넣기
        ctx.font = '60px Comic Sans Ms';
        ctx.fillStyle = 'red';
        ctx.textAlign = 'center';
        ctx.fillText('Hello World', canvas.width/2, canvas.height/2);
    }
</script>
</head>
<body>
<!-- canvas 그림그리기 javascript 이용-->
<canvas id="canvas" width="500" height="200"></canvas>

</body>
</html>


10
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #canvas { border:1px solid black; }
</style>
<script type="text/javascript">
    window.onload = function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        //canvas에 이미지 넣기
        var image = new Image();
        image.src = './images/Tulips.jpg';
        image.onload = function(){
            ctx.drawImage(image,0,0);
        }
    }
</script>
</head>
<body>
<!-- canvas 그림그리기 javascript 이용-->
<canvas id="canvas" width="500" height="200"></canvas>

</body>
</html>


11
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
div{
    font-size: 30px;
    border: 1px solid blue;
    padding: 10px;
}
</style>
<script type="text/javascript">
    var context;
    var dig;
    
    var dialImg = new Image();
    var hourImg = new Image();
    var minImg = new Image();
    var secImg = new Image();
    
    dialImg.src = "images/dial.png";
    hourImg.src = "images/pin_3.png";
    minImg.src = "images/pin_2.png";
    secImg.src = "images/pin_1.png";
    
    var rHour = 0.0, rMin=0.0, rSec=0.0;
    var centerX, centerY;
    
    window.onload=function(){
        var canvas=document.getElementById('myCanvas');
        dig = document.getElementById('digital');
        context = canvas.getContext('2d');
        
        centerX=300/2;
        centerY=300/2;
        
        setInterval(showTime, 50);
    }
    
    function drawCanvas(){
        context.drawImage(dialImg, centerX-150, centerY-150, 300, 300);
        context.save();
        
        context.translate(centerX, centerY);
        context.rotate(rSec);
        context.drawImage(secImg, -10, -130, 20, 130);
        context.restore();
        context.save();
        
        context.translate(centerX, centerY);
        context.rotate(rMin);
        context.drawImage(minImg, -10, -130, 20, 130);
        context.restore();
        context.save();
        
        context.translate(centerX, centereY);
        context.rotate(rHour);
        context.drawImage(hourImg, -10, -130, 20, 130);
        context.restore();
    }
    
    function showTime() {
        var d = new Date();
        var hour = d.getHours();
        var min = d.getMinutes();
        var sec = d.getSeconds();
        
        rSec = (6 * sec) * (Math.PI / 180);
        rMin = (6 * min) * (Math.PI / 180) + (6 * rSec / 360);
        rHour = (30 * hour) * (Math.PI / 180) + (30 * rMin / 360);
        drawCanvas();
        
        log(hour + "시 " + min + "분 " + sec + "초")
    }
    
    function log(msg) {
        dig.innerHTML = msg;
    }
</script>
</head>
<body>
    <div align="center">
        <canvas id="myCanvas" width="300" height="300"></canvas>
        <p font‐size="50px">현재시각</p>
        <div id="digital" style="width: 300px; border: 2px solid red; font‐size: 30px"></div>
    </div>
</body>
</html>


12
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //HTML5 Geolocation  //모바일 활용을 위해서 만들어짐, 컴퓨터는 네트워크를 통해서 geo를 받아옴
    var result;
    window.onload= function(){
        result = document.getElementById('result');
        if(navigator.geolocation){
            //result.innerHTML = 'Geolocation 지원';
            //컴퓨터의 geo정보를 가져오는데 시간이 걸리기때문에 callback - 함수 호출기법 사용
            navigator.geolocation.getCurrentPosition(showPosition);
            /* navigator.geolocation.getCurrentPosition(function(){
                alert('showPosition 호출')
            }); */
        }else{
            result.innerHTML = 'Geolocation 미지원';
        }
    };
    var showPosition = function(position){
        alert('showPosition 호출');
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        
        var msg = '위도 : '+latitude + '/ 경도 : ' + longitude;
        result.innerHTML=msg;
    };
</script>
</head>
<body>

<div id='result'></div>

</body>
</html>


13
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //HTML5 Geolocation  //모바일 활용을 위해서 만들어짐, 컴퓨터는 네트워크를 통해서 geo를 받아옴
    var result;
    window.onload= function(){
        result = document.getElementById('result');
        if(navigator.geolocation){
            //getCurrentPosition(정상출력, 비정상일때 출력)
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        }else{
            result.innerHTML = 'Geolocation 미지원';
        }
    };
    var showPosition = function(position){
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        
        var msg = '위도 : '+latitude + '/ 경도 : ' + longitude;
        result.innerHTML=msg;
    };
    //에러 처리
    var showError = function(error) {
        switch(error.code) {
            case error.PERMISSION_DENIED:
                result.innerHTML = "User denied the request for Geolocation."
                break;
            case error.POSITION_UNAVAILABLE:
                result.innerHTML = "Location information is unavailable."
                break;
            case error.TIMEOUT:
                result.innerHTML = "The request to get user location timed out."
                break;
            case error.UNKNOWN_ERROR:
                result.innerHTML = "An unknown error occurred."
                break;
        }
    }
</script>
</head>
<body>

<div id='result'></div>

</body>
</html>


14. 자바스크립트로 구글지도 api 불러오기
구글에서 api key를 받아야함
https://developers.google.com/maps/documentation/javascript/?hl=ko


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    * {margin: 0; padding: 0;}
    html, body{ height:100%;}
    #map {height: 100%;}
</style>
<!-- 구글 지도 자바스크립트 라이브러리 가져옴 -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=구글제공개인KEY&sensor=false"></script>
<script type="text/javascript">
    window.onload = function(){
        var element = document.getElementById('map');
        //맵 표시
        var map = new google.maps.Map(element,{
            zoom: 14,
            center: new google.maps.LatLng(37.49865608828099,127.02834066144196),
            mapTypeId: google.maps.MapTypeId.ROADMAP
            //mapTypeId: google.maps.MapTypeId.SATELLITE  //위성
            //mapTypeId: google.maps.MapTypeId.HYBRID   //로드맵 + 위성
        });
        
        //위치 표시
        new google.maps.Marker({
            position: new google.maps.LatLng(37.49865608828099,127.02834066144196),
            map: map,
            title: 'Hello Position'
        })
    }
</script>
</head>
<body>

<div id="map"></div>

</body>
</html>


15
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    * {margin: 0; padding: 0;}
    html, body{ height:100%;}
    #map {height: 100%;}
</style>
<!-- 구글 지도 자바스크립트 라이브러리 가져옴 -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=구글제공API키&sensor=false"></script>
<script type="text/javascript">
    window.onload = function(){
        var element = document.getElementById('map');
        
        //현재위치 확인
        navigator.geolocation.getCurrentPosition(function(position){
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            
            //맵 표시
            var map = new google.maps.Map(element,{
            zoom: 14,
            center: new google.maps.LatLng(latitude,longitude),
            mapTypeId: google.maps.MapTypeId.ROADMAP
            });
        

            //위치 표시
            new google.maps.Marker({
            position: new google.maps.LatLng(latitude,longitude),
            map: map
            });    
        }, function(error){
            alert('error');
        });
    };
    
</script>
</head>
<body>

<div id="map"></div>

</body>
</html>


16
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #target { width: 350px; height: 70px; padding: 10px; border: 1px solid black; }
</style>
<script type="text/javascript">
    var allowDrop=function(e){
        //dragover 대한 기본 이벤트 제거
        e.preventDefault();
    };
    
    var drag = function(e){
        //img - html 태그 - id값
        e.dataTransfer.setData('text', e.target.id);
    };
    var drop = function(e){
        e.preventDefault();
        var data = e.dataTransfer.getData('text');
        e.target.appendChild(document.getElementById(data));
    };
    
</script>
</head>
<body>
<!-- 드롭했을때, 드롭완료시 이벤트 검 -->
<div id="target" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<br />
<!-- 이미지를 드레그 가능하게 만듦, 드레그를 시작할 떄 이벤트검 -->
<img src="./images/img_logo.gif" width="336" height="69" id="drag1" draggable="true" ondragstart="drag(event)"/>
</body>
</html>


17
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #div1, #div2
    {float:left; width:100px; height:35px; margin:10px;padding:10px;border:1px solid #aaaaaa;}
</style>
<script type="text/javascript">
    function allowDrop(ev) {
        ev.preventDefault();
    }
    
    function drag(ev) {
        ev.dataTransfer.setData("text", ev.target.id);
    }
    
    function drop(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
</script>
</head>
<body>
    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
      <img src="./images/img_logo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
    </div>
    
    <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</body>
</html>


18
사용자의 데이터가 모두 날라가는 것을 막기 위한 저장장치

  • cookie : 클라이언트에게 노출되는 문제가 있음
  • localStorage
  • sessionStorage
  • 데이터베이스

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    var date = new Date();
    //7일동안 보관후 없어짐
    date.setDate(date.getDate() + 7);
    
    var willCookie = '';
    willCookie += 'CookieName = Value;';
    willCookie += 'expires=' +date.toUTCString;
    
    //쿠키저장
    document.cookie = willCookie;
</script>
</head>
<body>

</body>
</html>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<script type="text/javascript">
    alert('쿠키 :' + document.cookie);
</script>

</body>
</html>


19
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    window.onload= function(){
        var result1 = document.getElementById('result1');
        var result2 = document.getElementById('result2');
        
        if(window.localStorage){
            //영구저장소  //개발자 도구에서 지우지 않는한 계속 남아 있음
            result1.innerHTML = 'localStorage 지원';
        }
        if(window.sessionStorage){
            //임시저장소  //브라우저를 껐다가 키면 지워짐
            result2.innerHTML = 'sessionStorage 지원';
        }
        
        
        document.getElementById('btn11').onclick = function(){
            localStorage.key1 = '값1';  //값을 로컬저장소에 저장
        }
        document.getElementById('btn12').onclick = function(){
            result1.innerHTML = 'key1 : '+ localStorage.key1;
        }
        document.getElementById('btn21').onclick = function(){
            sessionStorage.key1 = '값2'; //값을 세션저장소에 저장
        }
        document.getElementById('btn22').onclick = function(){
            result2.innerHTML = 'key1 : '+ sessionStorage.key1;
        }
        
    }
</script>
</head>
<body>

<button id="btn11">localStorage 쓰기</button>
<button id="btn12">localStorage 읽기</button>

<button id="btn21">sessionStorage 쓰기</button>
<button id="btn22">sessionStorage 읽기</button>

<hr />

<div id='result1'></div>
<div id='result2'></div>

</body>
</html>


댓글 없음:

댓글 쓰기