building windows 8 metro style casual games using html5 and javascript
TRANSCRIPT
Building Windows 8 Metro Style casual games using HTML5 and JavaScript
Dave IsbitskiSr. Developer Evangelistblogs.msdn.com/[email protected]@microsoft.com
AgendaHTML5, CSS3 and IE 10
HTML5 Canvas and Game Loop
Camera
Touch
Accelerometer
WinJS Controls
You can build amazing sites and Metro style apps with the Windows 8 web platform
Windows 8
Windows Core OS Services
JavaScript(Chakra)
CC++
C#VB
Metro style Apps
Communication
& Data
Application Model
Devices & Printing
WinRT APIsGraphics &
Media
XAML HTML / CSS
HTMLJavaScri
pt
CC++
C#VB
Desktop Apps
Win32
.NET / SL
Internet Explore
r
Syst
em
Serv
ices
Vie
wM
od
el
Contr
olle
rC
ore Windows Core OS Services
Communication
& Data
Application Model
Devices & Printing
Graphics & Media
Syst
em
Serv
ices
Core
HTML 5
IE9 hardware-accelerated web platform
CSS 2D Transforms
CSS Backgrounds & Borders
CSS Color
CSS Fonts
CSS Media Queries
CSS Namespaces
CSS OM Views
CSS Selectors
CSS Values and Units
Data URI
DOM Element Traversal
DOM HTML
DOM Level 3 Core
DOM Level 3 Events
DOM Style
DOM Traversal and Range
DOMParser and XMLSerializer
ECMAScript 5
HTML5 Canvas
HTML5 Geolocation
HTML5 Selection
HTML5 semantic elements
HTML5 video and audio
ICC Color Profiles
Selectors API Level 2
SVG, standalone and in HTML
XHTML/XML
Windows 8 hardware-accelerated web platform
CSS 2D Transforms
CSS 3D Transforms
CSS Animations
CSS Backgrounds & Borders
CSS Color
CSS Flexbox
CSS Fonts
CSS Grid Alignment
CSS Hyphenation
CSS Image Values (Gradients)
CSS Media Queries
CSS multi-column Layout
CSS Namespaces
CSS OM Views
CSS Positioned Floats (Exclusions)
CSS Selectors
CSS Transitions
CSS Values and Units
Data URI
DOM Element Traversal
DOM HTML
DOM Level 3 Core
DOM Level 3 Events
DOM Style
DOM Traversal and Range
DOMParser and XMLSerializer
ECMAScript 5
File APIs
FormData
HTML5 Application Cache
HTML5 async
HTML5 Canvas
HTML5 Drag and drop
HTML5 Forms and Validation
HTML5 Geolocation
HTML5 History API
HTML5 Parser
HTML5 Sandbox
HTML5 Selection
HTML5 semantic elements
HTML5 video and audio
ICC Color Profiles
IndexedDB
Page Visibility
Pointer (Mouse, Pen, and Touch) Events
Selectors API Level 2
Filter Effects
SVG, standalone and in HTML
Timing callbacks
Web Messaging
Web Sockets
Web Workers
XHTML/XML
XMLHttpRequest (Level 2)
Popular CSS3 features in Windows 8
2D & 3D transforms
Transforms Animations
Transitions
MotionGrid
Flexbox
Layout
Gradients
Filter Effects
Text-shadow
GraphicsMulti-column, hyphenation
Pagination
Position float
Content flow
Windows hardware acceleration makes these beautiful and fast
CSS3 Features – Transforms, Web Fonts and Styles
demo
Popular HTML5 features in Windows 8Web Sockets
Web Workers
IndexedDB
Ecmascript 5
File API & Blobs
Geolocation
Audio tag
Video tag
Touch-first
Pointer events
Zoom regions
Snap Points
Forms
Validation
Input types
Spell checking
HTML5 Features – Strict Mode, VS2012, Audio Tags
demo
HTML5 Canvas
The Power of the Whole PC
GREETINGS PROFESSOR FALKEN.
WOULD YOU LIKE TO PLAY AGAME OF CHESS?
█
HTML5 Canvas Dynamic, scriptable rendering of 2D shapes and bitmaps
Simple API; 45 methods and 21 attributes
Typically hardware-accelerated
• state void save(); void restore();
• transformations void scale(…); void rotate(…); void translate(…); void transform(…); void setTransform(…);
• compositing globalAlpha; globalCompositeOperation;
• colors and styles strokeStyle; fillStyle; CanvasGradient
createLinearGradient(…); CanvasGradient
createRadialGradient(…); CanvasPattern createPattern(…);
• Line caps/joins attribute double lineWidth; attribute DOMString lineCap; attribute DOMString lineJoin; attribute double miterLimit;
• Shadows attribute double shadowOffsetX; attribute double shadowOffsetY; attribute double shadowBlur; attribute DOMString shadowColor;
• Rects void clearRect(…); void fillRect(…); void strokeRect(…);
• path API void beginPath(); void closePath(); void moveTo(…); void lineTo(…); void quadraticCurveTo(…); void bezierCurveTo(…); void arcTo(…); void rect(…); void arc(…); void fill(); void stroke(); void clip(); boolean isPointInPath(…);
• focus management boolean drawFocusRing(…);
• drawing images void drawImage(…);
• text attribute DOMString font; attribute DOMString textAlign; attribute DOMString textBaseline; void fillText(…); void strokeText(…); TextMetrics measureText(…);
• pixel manipulation ImageData createImageData(…); ImageData createImageData(…); ImageData getImageData(…); void putImageData(…);
• interface CanvasGradient { void addColorStop(…); };
• interface CanvasPattern {}; • interface TextMetrics {
readonly attribute double width; }; • interface ImageData {
readonly attribute unsigned long width; readonly attribute unsigned long height; readonly attribute CanvasPixelArray
data; }; • interface CanvasPixelArray {
readonly attribute unsigned long length; getter octet (…); setter void (…); };
Canvas on One Canvas!
Via Jatinder Mann – MIX11
HTML5 Canvas
HTML5 Element Bitmap Based JavaScript Driven
2D API Rectangles, Paths, Lines,
Fills, Arcs, Curves, etc.
“Immediate Mode”
<canvas>U haz an old browser
</canvas>
control
fallback
Canvas 101
<canvas id="myCanvas" width="200" height="200"> No canvas support.</canvas>
<script type="text/javascript"> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(255,0,0)"; ctx.fillRect(30, 30, 50, 50); </script>
CanvasPad
demo
Gameloop
Game Loop Overview
All games do three things
Load content when they startUpdate the game worldDraw the game world
Efficient code (performance and memory use) is critical!
Initialize Engine
Load Resources
Free Resources
Get User Input
Calculate
Test Criteria
Give FeedBack
Typical Game Loop
22
var FPS = 30;
init(){ // Load content/graphics here
// Start game loopsetInterval(gameLoop, 1000/FPS);
}
gameLoop(){// Update (Figure out what’s happening)// Draw (Show what’s happening)
}
Game Loop - setInterval
function update() {
//RequestAnimationFrame faster pef than setInterval anim = window.msRequestAnimationFrame(update);
if (menuEnabled) { drawStars(); } else { //Game Loop updateShips(); drawShips(); }}
Game Loop - requestAnimationFrame
Stuff for Games HTML5 Gaming Libraries
github.com/bebraw/jswiki/wiki/Game-Engines
EaselJS EaselJS.com
Sample Game Apps (XNA, etc.) create.msdn.com/en-US/education/catalog
Tons of Frameworks MakeAwesomeWeb.com
Demos and More IETestDrive.com
Space Cadet - Canvas and Gameloop
demo
Touch
Windows 8 is a touch-first OS
Windows 8 Touch Interactions
Press and hold to learn Tap for primary action Slide to drag Swipe to select
Pinch to zoomSwipe from edge for app commandsRotate to rotate
Swipe from edge for system commands
Touch Platform Goals Unify touch mouse and pen into a single pointer input AP
Express the touch interaction language in the platform
"Code for touch, get mouse and pen for free!"
Pointer Events Pointer unifies all "pointing" devices into a single, consistent set of interfaces and events Input-specific properties allow you to provide a differentiated UX
when you want one
DOM pointer events follow the familiar pattern of mouse events, with extensions for touch properties and interaction principles If you know how to code for mouse input, you know the basics of
coding for pointer input!
Pointer Events in the DOM
MSPointerDown, MSPointerUpMSPointerMoveMSPointerOver, MSPointerOut, MSPointerHoverMSPointerCancel
Basic DOM pointer events:
Derives from the same event class
Includes capture/bubble phase
Pointer events behave similarly to mouse events
Position (in the usual choice of coordinate systems)
Pointer type (touch, mouse, pen)
Contact id
Commonly used event properties:
Touch – Space Cadet Touch
demo
Camera
Windows.Media APIsSnap a picture, record video and audio.Capture
Windows.Media.
Input and output audio devices such as Bluetooth.Devices
Work with audio playlists.Playlists
Stream media to a television or audio system.PlayTo
Use PlayReady or other content protection systems.Protection
Convert music or video to other formats or resolutions, trim, or make effects permanent.
Transcoding
Insert or remove well-known video effects.VideoEffects
• Camera Capture UI Similar to ‘pick’ photos or videos from the file system Built-in camera control with pre-defined user workflow
• Media Capture API You control every pixel on screen Custom User Experience and workflow
Windows.Media APIsCapture
Windows.Media.
CameraCaptureUI
MediaCapture
Accessing Camera and Mic from your app
// Application manifest capabilities required to access camera and microphone<Capabilities> <DeviceCapability Name="webcam" /> <DeviceCapability Name="microphone" /></Capabilities>
Using the camera to snap a photo<body><p id="message"></p><img id="imagedisplay" /><script type="text/javascript"> // Step 1: Invoke the camera capture UI for snapping a photovar captureUI = new Windows.Media.Capture.CameraCaptureUI();captureUI.captureFileAsync(Windows.Media.CameraCaptureUI.Mode.photo). then(function(capturedItem) {
if (capturedItem) { // Step 2: Display the photo document.getElementById("imagedisplay").src = URL.createObjectURL(capturedItem); } else { document.getElementById("message").innerHTML = "User didn’t capture a photo"; }
}); </script></body>
Camera – Space Cadet Photo
demo
Accelerometer
Accelerometer Sample Codevar accelerometer;accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();accelerometer.addEventListener("readingchanged",onAccReadingChanged);
function onAccReadingChanged(e) { var accelX = e.reading.accelerationX; var accelY = e.reading.accelerationY; var accelZ = e.reading.accelerationZ;}
Accelerometer – Gravity Pulse
demo
WinJS
Windows Library for JavaScript (WinJS)library for building Metro style apps using JavaScript
Web technologies you’re already familiar with
Modern patterns for responsive, reliable apps
Use interactive design tools
Build your apps fast and with high quality
Matches the Windows Metro design style
Controls for common user experiences
Designed for touch as well as traditional input
Scales across form factors
Make your apps look and feel great
WinJSHelpers for Namespaces, Constructor Definition
Promises
App Model
Navigation
Page & User controls
Data binding
Controls
Animations
Templates
Utilities
Default CSS Styles
WinJS – App, AppBar, ViewBox
demo
If you know web technologies, you are ready to build amazing Metro style apps.
Building Windows 8 Metro Style casual games using HTML5 and JavaScript
Dave IsbitskiSr. Developer Evangelistblogs.msdn.com/[email protected]@microsoft.com