04-20 07:13
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[WebApp / CreateJS] 간단한 오브젝트 생성 + 터치 무브 + 사운드 재생 본문

Programming/Web App

[WebApp / CreateJS] 간단한 오브젝트 생성 + 터치 무브 + 사운드 재생

cinema4dr12 2015. 12. 9. 23:23

이번 글에서는 CreateJS를 이용하여 간단한 오브젝트들을 생성하고, 오브젝트들을 마우스 드래그 또는 터치 드래그(터치패드의 경우)하고, 클릭(터치)하는 동안 각각의 사운드가 출력되도록 하는 예제를 살펴 보도록 한다.


Part 1 - CreateJS 라이브러리 로딩하기


CreateJS Suite는 HTML5의 Canvas 기술을 기반으로하여 Web Browser에서 풍부한 상호작용(interactive) 콘텐츠 기술을 표현하기 위한 JavaScript 라이브러리로써 gskinner가 처음 개발한 후 Adobe, MS, Mozilla 재단 등이 post-Flash를 위하여 적극적으로 후원하고 있다.

(ActionScript와 유사하여 기존의 Flash 개발자들은 금방 적응할 것이다.)

CreateJS Suite는 다음 다섯 가지의 JavaScript 라이브러리로 구성된다:

(1) EaselJS

HTML5 Canvas에 Graphic 객체 생성을 위한 라이브러리이다.

(2) TweenJS

객체의 상태 등을 보간하는 기능을 제공하는 라이브러리이다.

(3) SoundJS

사운드 재생을 위한 기능을 제공하는 라이브러리이다.

(4) PrelodJS

사운드, 그래픽 객체, 텍스트, JavaScript 코드 등을 사전에 로딩하는 기능을 제공하는 라이브러리이다.

(5) Zoë

SWF 애니메이션을 sprite sheet으로 변환하는 Adobe AIR 어플리케이션이다.


HTML 문서에서 다음을 입력하여 CreateJS 라이브러리를 로딩한다:


Part 2 - Canvas 태그 작성


다음과 같이 HTML의 <body> 태그 내 <canvas> 태그를 작성한다:


여기서 중요한 것은 <canvas> 태그의 id인데 이것은 CreateJS의 container 객체와 연결되기 때문이다.



Part 3 - Sound ID 정의 & JavaScript 함수 작성


<script> 태그 내에 전역 배열 변수로 3개의 요소(element)를 갖는 sound ID를 정의한다:


Sound 관련 함수를 작성한다:



Part 4 - init() 함수 정의


HTML의 <body> 태그에 로딩 시 실행될 함수를 다음과 같이 정의한다:


이제 init() 함수를 정의한다:



Part 5 - 전체 코드


이해를 돕기 위하여 HTML 전체를 다음과 같이 수록하였다.

<!DOCTYPE html>
<html lang="en">
<head>
<title>CreateJS</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
   body {
      font-family: Monospace;
      background-color: #f0f0f0;
      margin: 0px;
      overflow: hidden;
   }
</style>
</head>

<script src="https://code.createjs.com/easeljs-0.8.1.min.js"></script>
<script src="https://code.createjs.com/createjs-2015.05.21.min.js"></script>
<script src="https://code.createjs.com/tweenjs-0.6.1.min.js"></script>
<script src="https://code.createjs.com/tweenjs-0.6.1.min.js"></script>
<script src="https://code.createjs.com/preloadjs-0.6.2.min.js"></script>

<script>
var soundID = ["sound_01", "sound_02", "sound_03"];

function init() {
   // state: <canvas> 태그의 id와 연결되며 객체들의 container이다.
   var stage = new createjs.Stage("demoCanvas");

   // 원 객체
   var circle = new createjs.Shape();

   // 직사각형 객체
   var rect = new createjs.Shape();

   // 둥근 모서리 직사각형 객체
   var roundRect = new createjs.Shape();

   // sound를 모두 로딩한다.
   loadSound();

   // circle을 생성하고 위치를 정의하고 stage에 포함시킨다.
   circle.graphics.beginFill("#ffbf00").drawCircle(0, 0, 50);
   circle.x = 100;
   circle.y = 100;
   stage.addChild(circle);

   // rect를 생성하고 위치를 정의하고 stage에 포함시킨다.
   rect.graphics.beginFill("#00bfff").drawRect(0, 0, 100, 100);
   rect.x = 300;
   rect.y = 300;
   stage.addChild(rect);

   // roundRect를 생성하고 위치를 정의하고 stage에 포함시킨다.
   roundRect.graphics.beginFill("#bfff00").drawRoundRect(0, 0, 100, 100, 20);
   roundRect.x = 100;
   roundRect.y = 300;
   stage.addChild(roundRect);

   // touch에 반응할 수 있도록 한다.
   createjs.Touch.enable(stage);

   // 매 프레임마다 stage를 업데이트 한다.
   createjs.Ticker.addEventListener("tick", stage);

   // circle 오브젝트에 대한 이벤트 처리를 한다.
   circle.addEventListener('mousedown',function(e) {
      stopSound();
      playSound(0);

      stage.addEventListener('stagemousemove',function(e) {
         circle.x = stage.mouseX;
         circle.y = stage.mouseY;
      });

      stage.addEventListener('stagemouseup',function(e) {
         e.target.removeAllEventListeners();
      });

   });

   // rect 오브젝트에 대한 이벤트 처리를 한다.
   rect.addEventListener('mousedown',function(e) {
      stopSound();
      playSound(1);

      stage.addEventListener('stagemousemove',function(e) {
         rect.x = stage.mouseX;
         rect.y = stage.mouseY;
      });

      stage.addEventListener('stagemouseup',function(e) {
         e.target.removeAllEventListeners();
      });

   });

   // roundRect 오브젝트에 대한 이벤트 처리를 한다.
   roundRect.addEventListener('mousedown',function(e) {
      stopSound();
      playSound(2);

      stage.addEventListener('stagemousemove',function(e) {
         roundRect.x = stage.mouseX;
         roundRect.y = stage.mouseY;
      });

      stage.addEventListener('stagemouseup',function(e) {
         e.target.removeAllEventListeners();
      });

   });

}

// sound를 로드한다.
function loadSound () {
   createjs.Sound.registerSound("../assets/audio/sound_01.mp3", soundID[0]);
   createjs.Sound.registerSound("../assets/audio/sound_02.mp3", soundID[1]);
   createjs.Sound.registerSound("../assets/audio/sound_03.mp3", soundID[2]);
}

// sound를 재생한다.
function playSound (idx) {
   createjs.Sound.play(soundID[idx]);
}

// sound를 중지한다.
function stopSound () {
   createjs.Sound.stop(soundID[0]);
   createjs.Sound.stop(soundID[1]);
   createjs.Sound.stop(soundID[2]);
}

</script>

<body onload="init();">
   <canvas id="demoCanvas" width="1146" height="1000"></canvas>
</body>

</html>
 


Comments