웹 앱 구성

웹 앱은 Interactive Canvas를 사용하는 작업의 사용자 인터페이스 (UI)입니다. 기존 웹 기술 (예: HTML, CSS, JavaScript, WebAssembly)을 사용하여 웹 앱을 디자인하고 개발할 수 있습니다. 대부분의 경우 Interactive Canvas는 브라우저처럼 웹 콘텐츠를 렌더링할 수 있지만 사용자 개인 정보 보호 및 보안을 위해 몇 가지 제한사항이 적용됩니다. UI 디자인을 시작하기 전에 디자인 가이드라인에 설명된 디자인 원칙을 고려하세요. 웹 앱을 배포하려면 Firebase 호스팅을 사용하는 것이 좋습니다.

웹 앱의 HTML 및 JavaScript는 다음을 수행합니다.

이 페이지에서는 웹 앱을 빌드하는 권장 방법, 대화형 작업과 웹 앱 간의 통신을 사용 설정하는 방법, 일반적인 가이드라인과 제한사항을 설명합니다.

모든 방법으로 UI를 빌드할 수 있지만 다음 라이브러리를 사용하는 것이 좋습니다.

  • Greensock: 복잡한 애니메이션을 빌드하는 데 적합합니다.
  • Pixi.js: WebGL에서 2D 그래픽을 그리는 데 사용됩니다.
  • Three.js: WebGL에서 3D 그래픽을 그리는 데 사용됩니다.
  • HTML5 캔버스 그리기: 간단한 그림에 적합합니다.

아키텍처

단일 페이지 애플리케이션 아키텍처를 사용하는 것이 좋습니다. 이 접근 방식은 최적의 성능을 제공하며 지속적인 대화형 사용자 환경을 지원합니다. Interactive Canvas는 상태 관리에 도움이 되는 Vue, Angular, React 같은 프런트엔드 프레임워크와 함께 사용할 수 있습니다.

HTML 파일

HTML 파일은 UI의 모양을 정의합니다. 또한 이 파일은 웹 앱과 대화형 작업 간의 커뮤니케이션을 지원하는 Interactive Canvas API도 로드합니다.

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Interactive Canvas Sample</title>

    <!-- Disable favicon requests -->
    <link rel="shortcut icon" type="image/x-icon" href="data:image/x-icon;,">

    <!-- Load Interactive Canvas JavaScript -->
    <script src="https://www.gstatic.com/assistant/interactivecanvas/api/interactive_canvas.min.js"></script>

    <!-- Load PixiJS for graphics rendering -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.8.7/pixi.min.js"></script>

    <!-- Load Stats.js for fps monitoring -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js"></script>

    <!-- Load custom CSS -->
    <link rel="stylesheet" href="css/main.css">
  </head>
  <body>
    <div id="view" class="view">
      <div class="debug">
        <div class="stats"></div>
        <div class="logs"></div>
      </div>
    </div>
    <!-- Load custom JavaScript after elements are on page -->
    <script src="js/log.js"></script>
    <script type="module" src="js/main.js"></script>
  </body>
</html>
    

대화형 작업과 웹 앱 간 통신

웹 앱과 대화형 작업을 빌드하고 웹 앱 파일의 Interactive Canvas 라이브러리에 로드한 후에는 웹 앱과 대화형 작업이 상호작용하는 방식을 정의해야 합니다. 이렇게 하려면 웹 앱 로직이 포함된 파일을 수정합니다.

action.js

이 파일에는 interactiveCanvas를 통해 callbacks을 정의하고 메서드를 호출하는 코드가 포함되어 있습니다. 콜백을 사용하면 웹 앱이 대화형 작업에서 정보나 요청에 응답할 수 있으며, 메서드는 대화형 작업으로 정보나 요청을 전송하는 방법을 제공합니다.

HTML 파일에 interactiveCanvas.ready(callbacks);를 추가하여 callbacks을 초기화하고 등록합니다.

JavaScript

/**
* This class is used as a wrapper for Google Assistant Canvas Action class
* along with its callbacks.
*/
export class Action {
 /**
  * @param  {Phaser.Scene} scene which serves as a container of all visual
  * and audio elements.
  */
 constructor(scene) {
   this.canvas = window.interactiveCanvas;
   this.gameScene = scene;
   const that = this;
   this.intents = {
     GUESS: function(params) {
       that.gameScene.guess(params);
     },
     DEFAULT: function() {
       // do nothing, when no command is found
     },
   };
 }

 /**
  * Register all callbacks used by the Interactive Canvas Action
  * executed during game creation time.
  */
 setCallbacks() {
   const that = this;
   // Declare the Interactive Canvas action callbacks.
   const callbacks = {
     onUpdate(data) {
       const intent = data[0].google.intent;
       that.intents[intent ? intent.name.toUpperCase() : 'DEFAULT'](intent.params);
     },
   };
   // Called by the Interactive Canvas web app once web app has loaded to
   // register callbacks.
   this.canvas.ready(callbacks);
 }
}
    

main.js

main.js 자바스크립트 모듈은 action.jsscene.js 파일을 가져와서 웹 앱이 로드될 때 각각의 인스턴스를 만듭니다. 이 모듈은 Interactive Canvas의 콜백도 등록합니다.

JavaScript

import {Action} from './action.js';
import {Scene} from './scene.js';
window.addEventListener('load', () => {
  window.scene = new Scene();
  // Set Google Assistant Canvas Action at scene level
  window.scene.action = new Action(scene);
  // Call setCallbacks to register Interactive Canvas
  window.scene.action.setCallbacks();
});
    

scene.js

scene.js 파일은 웹 앱의 장면을 구성합니다. 다음은 scene.js에서 발췌한 것입니다.

JavaScript

const view = document.getElementById('view');

// initialize rendering and set correct sizing
this.radio = window.devicePixelRatio;
this.renderer = PIXI.autoDetectRenderer({
  transparent: true,
  antialias: true,
  resolution: this.radio,
  width: view.clientWidth,
  height: view.clientHeight,
});
this.element = this.renderer.view;
this.element.style.width = `${this.renderer.width / this.radio}px`;
this.element.style.height = `${(this.renderer.height / this.radio)}px`;
view.appendChild(this.element);

// center stage and normalize scaling for all resolutions
this.stage = new PIXI.Container();
this.stage.position.set(view.clientWidth / 2, view.clientHeight / 2);
this.stage.scale.set(Math.max(this.renderer.width,
    this.renderer.height) / 1024);

// load a sprite from a svg file
this.sprite = PIXI.Sprite.from('triangle.svg');
this.sprite.anchor.set(0.5);
this.sprite.tint = 0x00FF00; // green
this.sprite.spin = true;
this.stage.addChild(this.sprite);

// toggle spin on touch events of the triangle
this.sprite.interactive = true;
this.sprite.buttonMode = true;
this.sprite.on('pointerdown', () => {
  this.sprite.spin = !this.sprite.spin;
});
    

터치 상호작용 지원

Interactive Canvas 작업은 사용자의 터치와 음성 입력에 응답할 수 있습니다. Interactive Canvas 디자인 가이드라인에 따라 작업을 '음성 우선'으로 개발해야 합니다. 하지만 일부 스마트 디스플레이는 터치 상호작용을 지원합니다.

터치 지원은 대화형 응답을 지원하는 것과 유사합니다. 하지만 클라이언트 측 JavaScript는 사용자의 음성 응답 대신 터치 상호작용을 찾고 이를 사용하여 웹 앱의 요소를 변경합니다.

Pixi.js 라이브러리를 사용하는 샘플에서 이에 관한 예를 확인할 수 있습니다.

JavaScript

…
this.sprite = PIXI.Sprite.from('triangle.svg');
…
this.sprite.interactive = true; // Enables interaction events
this.sprite.buttonMode = true; // Changes `cursor` property to `pointer` for PointerEvent
this.sprite.on('pointerdown', () => {
  this.sprite.spin = !this.sprite.spin;
});
    

문제 해결

작업 콘솔의 시뮬레이터를 사용하여 개발 중에 Interactive Canvas 작업을 테스트할 수 있지만 프로덕션 단계에 있는 사용자 기기의 Interactive Canvas 웹 앱에서 발생하는 오류를 확인할 수도 있습니다. 이러한 오류는 Google Cloud Platform 로그에서 확인할 수 있습니다.

Google Cloud Platform 로그에서 이러한 오류 메시지를 확인하려면 다음 단계를 따르세요.

  1. Actions 콘솔에서 작업 프로젝트를 엽니다.
  2. 상단 탐색 메뉴에서 Test(테스트)를 클릭합니다.
  3. Google Cloud Platform에서 로그 보기 링크를 클릭합니다.

사용자 기기의 오류는 로그 뷰어에 시간순으로 표시됩니다.

오류 유형

Google Cloud Platform 로그에서 확인할 수 있는 웹 앱 오류 유형에는 세 가지가 있습니다.

  • ready가 10초 이내에 호출되지 않을 때 발생하는 시간 제한
  • onUpdate()에서 반환된 프로미스가 10초 내에 처리되지 않을 때 발생하는 제한 시간
  • 웹 앱 내에서 포착되지 않는 JavaScript 런타임 오류

자바스크립트 오류 세부정보 보기

웹 앱 내의 자바스크립트 런타임 오류 세부정보는 기본적으로 제공되지 않습니다. 자바스크립트 런타임 오류의 세부정보를 확인하려면 다음 단계를 따르세요.

  1. 웹 앱 파일에 적절한 CORS(교차 출처 리소스 공유) HTTP 응답 헤더가 구성되었는지 확인합니다. 자세한 내용은 교차 출처 리소스 공유를 참고하세요.
  2. 다음 코드 스니펫과 같이 HTML 파일의 가져온 <script> 태그에 crossorigin="anonymous"를 추가합니다.
<script crossorigin="anonymous" src="<SRC>"></script>

가이드라인 및 제한사항

웹 앱을 개발할 때 다음 가이드라인과 제한사항을 고려하세요.

  • 쿠키 없음
  • 로컬 저장소 없음
  • 위치정보 없음
  • 카메라 사용 안함
  • 오디오 또는 동영상 녹화가 되지 않음
  • 팝업 없음
  • 메모리 한도 200MB 미만으로 유지
  • 콘텐츠를 렌더링할 때 작업 이름 헤더를 고려합니다 (화면 상단 점유).
  • 동영상에 스타일을 적용할 수 없습니다.
  • 한 번에 하나의 미디어 요소만 사용할 수 있습니다.
  • 웹 SQL 데이터베이스 없음
  • Web Speech APISpeechRecognition 인터페이스는 지원되지 않습니다.
  • 어두운 모드 설정을 적용할 수 없음
  • 스마트 디스플레이에서 동영상 재생이 지원됩니다. 지원되는 미디어 컨테이너 형식 및 코덱에 관한 자세한 내용은 Google Nest Hub 코덱을 참고하세요.

교차 출처 리소스 공유

Interactive Canvas 웹 앱은 iframe에서 호스팅되고 출처가 null로 설정되므로 웹 서버 및 스토리지 리소스에 교차 출처 리소스 공유 (CORS)를 사용 설정해야 합니다. 이 프로세스를 통해 애셋이 null 출처의 요청을 수락할 수 있습니다.

다음 단계

웹 앱에 기능을 더 추가하려면 클라이언트 또는 서버 측 처리로 계속 빌드를 참고하세요.