OReilly Supercharged JavaScript Graphics, With HTML5 Canvas and jQuery

This book is for those who have a good working knowledge of JavaScript and would like to experiment with graphics programming that goes beyond simple hover effects or relying purely on the animation facilities of libraries such as jQuery.


Raffaele Cecco


280 Pages

19318 Reads

77 Downloads

English

PDF Format

10.9 MB

Java Script

Download PDF format


  • Raffaele Cecco   
  • 280 Pages   
  • 13 Feb 2015
  • Page - 1

    read more..

  • Page - 2

    read more..

  • Page - 3

    read more..

  • Page - 4

    read more..

  • Page - 5

    read more..

  • Page - 6

    read more..

  • Page - 7

    read more..

  • Page - 8

    read more..

  • Page - 9

    read more..

  • Page - 10

    9. Reaching the Small Screen with jQuery Mobile ............................. 215 10. Creating Android Apps with PhoneGap ................................... 231 Index ..................................................................... 243 viii | Table of Contents read more..

  • Page - 11

    Preface ix read more..

  • Page - 12

    Audience and Assumptions Organization x | Preface read more..

  • Page - 13

    Preface | xi read more..

  • Page - 14

    Conventions Used in This Book Constant width Constant width bold Constant width italic Using Code Examples xii | Preface read more..

  • Page - 15

    <!DOCTYPE html> Target Browsers Safari® Books Online Preface | xiii read more..

  • Page - 16

    How to Contact Us Acknowledgments xiv | Preface read more..

  • Page - 17

    Preface | xv read more..

  • Page - 18

    read more..

  • Page - 19

    CHAPTER 1 Code Reuse and Optimization Class 1 read more..

  • Page - 20

    Pet Cat // Define a Pet object. Pass it a name and number of legs. var Pet = function (name, legs) { this.name = name; // Save the name and legs values. this.legs = legs; }; // Create a method that shows the Pet's name and number of legs. Pet.prototype.getDetails = function () { return this.name + ' has ' + this.legs + ' legs'; }; // read more..

  • Page - 21

    petCat legs prototype new // Define a pet object. Pass it a name and number of legs. var pet = function (name, legs) { // Create an object literal (that). Include a name property for public use // and a getDetails() function. Legs will remain private. // Any local variables defined here or passed to pet as arguments will remain // read more..

  • Page - 22

    Keeping It Fast 4 | Chapter 1: Code Reuse and Optimization read more..

  • Page - 23

    What and When to Optimize What and When to Optimize | 5 read more..

  • Page - 24

    6 | Chapter 1: Code Reuse and Optimization read more..

  • Page - 25

    Homespun Code Profiling var startTime = new Date().getTime(); // Run some test code here. var timeElapsed = new Date().getTime() - startTime; // Credit: based on code by John Resig. var startTime = new Date().getTime(); for (var iters = 0; timeElapsed < 1000; iters++) { // Run some test code here. Homespun Code Profiling | 7 read more..

  • Page - 26

    timeElapsed = new Date().getTime() - startTime; } // iters = number of iterations achieved in 1000 milliseconds. Optimizing JavaScript Lookup Tables Math.sin() Math.sin() π steps var fastSin = function (steps) { var table = [], ang = 0, angStep = (Math.PI * 2) / steps; do { table.push(Math.sin(ang)); read more..

  • Page - 27

    return table; }; fastSin() π sin Math.sin() Math.sin() fastSin() <!DOCTYPE html> <html> <head> <title> Fast Sine Demonstration </title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> read more..

  • Page - 28

    background-color:#000; position:relative; } </style> <script type="text/javascript"> $(document).ready(function() { (function() { var fastSin = function(steps) { read more..

  • Page - 29

    drawGraph() div var drawGraph = function(ang, freq, height) { var height2 = height * 2; for (var i = 0; i < 480; i++) { bars[i].style.top = read more..

  • Page - 30

    Bitwise Operators, Integers, and Binary Numbers int float ± ± alert(0.1 + 0.2) ToInteger ToInt32 ToUint32 ToUint16 A quick recap of binary numbers 12 | Chapter 1: Code Reuse and Optimization read more..

  • Page - 31

    10,000 1,000 100 10 1 0 3 0 0 9 128 64 32 168421 0 1 0 0 0 1 0 1 JavaScript’s bitwise operators 0x0007 & 0x0003 0x0003 pet Bitwise AND (x & y). Optimizing JavaScript | 13 read more..

  • Page - 32

    Big Small Young Old Brown White Dog Cat 128 64 32 16 8 4 2 1 pet pet var searchFlags = 128 + 32 + 4; var pets = []; // This is an array full of pet objects. var numPets = pets.length; for (var i = 0; i < numPets; i++) { if (searchFlags & pets[i].flags === searchFlags) { /* Found a Match! Do something. */ } } var search = read more..

  • Page - 33

    toggle ^= 1; toggle ^= 1; toggle if-else if (toggle) { toggle = 0; }else { toggle = 1; } ? toggle = toggle ? 0:1; ~ x 2^numBits y = 5 << 1; // y = 10; Equivalent to Math.floor(5 * (2^1)). y = 5 << 2; // y = 20; Equivalent to Math.floor(5 * (2^2)). y = 5 << 3; // y = 40; Equivalent to Math.floor(5 * (2^3)). * x 2^numBits y = 10 read more..

  • Page - 34

    y = 10 >>> 1; // y = 5; y = −10 >>> 2; // y = 1073741821; y = −10 >>> 3; // y = 536870910; Loop unrolling: An inconvenient truth for (var i = 0; i < 8; i++) { /*** do something here **/ } /*** do something here ***/ /*** do something here ***/ /*** do something here ***/ /*** do something here ***/ /*** do something here ***/ read more..

  • Page - 35

    here // Credit: from Jeff Greenberg's site via an anonymous donor. var testVal = 0; var n = iterations % 8 while (n--) { testVal++; } n = parseInt(iterations / 8); while (n--) { testVal++; testVal++; testVal++; testVal++; testVal++; testVal++; testVal++; testVal++; } } while 1004 % 8 parseInt(1004 / 8) var read more..

  • Page - 36

    testVal++; testVal++; testVal++; } n = iterations - testVal; // testVal has kept a tally, so do the remainder here. while(n--) { testVal++; } // Initialize 10000 items. var items = []; for (var i = 0; i < 10000; i++) { items.push(Math.random()); } 18 | Chapter 1: Code Reuse and Optimization read more..

  • Page - 37

    // A function to do some useful work. var processItem = function (x) { return Math.sin(x) * 10; }; // The slow way. var slowFunc = function () { var len = items.length; for (var i = 0; i < len; i++) { processItem(items[i]); } }; // The 'fast' way. var fastFunc = function () { var idx = 0; var i read more..

  • Page - 38

    big $images = jQuery('img.big'); $images = $('img.big'); $images $ Optimizing CSS Style Changes $('#element1').css('color','#f00'); id element1 color 20 | Chapter 1: Code Reuse and Optimization read more..

  • Page - 39

    id element1 css() $('#element1').css('color','#f00'); // Make red. $('#element1').css('color','#0f0'); // Make green. $('#element1').css('color','#00f'); // Make blue. $('#element1').css('left,'100px'); // Move a bit. id element1 document alien container $aliens = $('.alien', container); // Search within a specific DOM element. // Start search within the elements of the jQuery read more..

  • Page - 40

    css() // Get the first element ([0]) from the jQuery search results and store // a reference to the style object of that element in elemStyle. var elemStyle = $('#element1')[0].style; // It is now quicker to manipulate the CSS styles of the element. // jQuery is not being used at all here: elemStyle.color = '#f00'; // Make red. elemStyle.color = '#0f0'; read more..

  • Page - 41

    Optimizing DOM Insertion $('#element1').append('<p>element to insert</p>'); var elements = ''; // First build up a string containing all the elements. for (var i = 0; i < 1000; i++) { elements += '<p>This is element ' + i + '</p>'; } // They can now be inserted all at once. $('#element1').append(elements); Other Resources Other Resources | 23 read more..

  • Page - 42

    read more..

  • Page - 43

    CHAPTER 2 DHTML Essentials Creating DHTML Sprites DHTMLSprite 25 read more..

  • Page - 44

    DHTMLSprite Image Animation img background-position div background-position div 26 | Chapter 2: DHTML Essentials read more..

  • Page - 45

    // This code is unoptimized, but illustrates the calculations required. var vertOffset = -Math.floor (index * 64 / 256) * 64; // 64 is the sprite height. var horizOffset = -(index * 64 % 256); // 64 is the sprite width. div // This code is unoptimized, but illustrates the calculations required. var vertOffset = -Math.floor (index * 32 / read more..

  • Page - 46

    Encapsulation and Drawing Abstraction (aka Hiding Stuff) DHTMLSprite Minimizing DOM Insertion and Deletion show hide DHTMLSprite DHTMLSprite The Sprite Code params DHTMLSprite params params params var DHTMLSprite = function (params) { Parameter Description images Path to the images file imagesWidth Pixel width of the images file width Pixel width of sprite height Pixel height of sprite $drawTarget The read more..

  • Page - 47

    var width = params.width, height = params.height, imagesWidth = params.imagesWidth, div params.$draw Target div $element $ style div elemStyle $element = params.$drawTarget.append('<div/>').find(':last'), elemStyle = $element[0].style, // Store a local reference to the Math.floor function for faster read more..

  • Page - 48

    div show: function () { elemStyle.display = 'block'; }, hide: function () { elemStyle.display = 'none'; }, destroy: function () { $element.remove(); } }; // Return the instance read more..

  • Page - 49

    var sprite1 = DHTMLSprite(params), sprite2 = DHTMLSprite(params); sprite2.changeImage(5); sprite1.draw(64, 64); sprite2.draw(352, 192); }); </script> read more..

  • Page - 50

    A More Dynamic Sprite Application bouncySprite DHTMLSprite bouncySprite DHTMLSprite bouncySprite DHTMLSprite var bouncySprite = function (params) { params DHTMLSprite bouncy Sprite var x = params.x, y = params.y, xDir = params.xDir, yDir = params.yDir, maxX = params.maxX, maxY = params.maxY, Parameter Description read more..

  • Page - 51

    x += xDir; y += yDir; animIndex % animIndex animIndex += xDir > 0 ? 1 : −1; animIndex %= 5; animIndex += animIndex < 0 ? 5 : 0; bouncySprite maxX maxY bouncySprite if ((xDir < 0 && x < 0) || (xDir > 0 && x >= maxX)) { xDir = read more..

  • Page - 52

    bouncys.push(bouncySprite({ images: '/images/cogs.png', imagesWidth: 256, width: 64, height: 64, $drawTarget: $drawTarget, x: Math.random() * ($drawTarget.width() - 64), y: Math.random() * read more..

  • Page - 53

    var bouncyBoss = function(numBouncy, $drawTarget) { /*** bouncyBoss code removed for conciseness ***/ }; $(document).ready(function() { bouncyBoss bouncySprite moveAndDraw bouncyBoss(50, $('#draw-target')); }); read more..

  • Page - 54

    bouncySprite bouncyBoss bouncySprite DHTMLSprite bouncy Sprite bouncyBoss ; // Initial solitary semicolon. $ jQuery() $() $ (function ($) { fn $.fn.bouncyPlugin = function (option) { DHTMLSprite bouncySprite bouncyBoss var DHTMLSprite = function (params) { /*** DHTMLSprite code removed for conciseness ***/ }; read more..

  • Page - 55

    /*** bouncyBoss code removed for conciseness ***/ }; option extend option $.fn.bouncyPlugin.defaults option defaults $.fn.bouncyPlugin.defaults option = $.extend({}, $.fn.bouncyPlugin.defaults, option); this this $drawTarget option $drawTarget bouncyBoss return this.each(function () { var $drawTarget = $(this); read more..

  • Page - 56

    ;(function($) { $.fn.bouncyPlugin = function(option) { /*** bouncyPlugin code removed for conciseness ***/ }; })(jQuery); draw-target $(document).ready(function() { read more..

  • Page - 57

    // This is a callback function. var bigFunction = function() { // Do something... // This code needs to be called regularly. // It takes 20ms to execute }; // setInterval will attempt to call bigFunction() every 50 milliseconds. setInterval(bigFunction, 50); bigFunction() setInterval(bigFunction, 15); bigFunction() Timers, Speed, and Frame Rate | 39 read more..

  • Page - 58

    setInterval(bigFunction, 5); setInterval() bigFunction() setInterval() setInterval() setTimeout() setInterval() setTimeout(bigFunction,50); bigFunction() setInterval() setTimeout() setInterval() // This is a callback function. var bigFunction = function() { // Do something... // This code needs to be called regularly. // It takes 20ms to execute setTimeout(bigFunction, 10); }; read more..

  • Page - 59

    Date() var startTime = new Date().getTime(); /*** Execute some code here that takes less than 15 milliseconds ***/ var endTime = new Date().getTime(); var elapsedTime = endTime - startTime; Achieving Consistent Speed Timers, Speed, and Frame Rate | 41 read more..

  • Page - 60

    Goal FPS Actual FPS Time coefficient 60 30 2 60 15 4 30 40 0.75 50 50 1 Date actualFPS = 1000 / (endTime - startTime); Frames per second Perceived smoothness Less than 15 Rather jerky 15–20 Just acceptable 20–30 Reasonably smooth 30–40 Smooth 40+ Very smooth timeInfo goalFPS 42 | Chapter 2: DHTML Essentials read more..

  • Page - 61

    goalFPS getInfo() getInfo() var timeInfo = function (goalFPS) { var oldTime, paused = true, interCount = 0, totalFPS = 0; totalCoeff = 0; return { getInfo: function () { Property Description elapsed The number of milliseconds since the last call to getInfo() coeff The coefficient to be used in movement and read more..

  • Page - 62

    var coeff = goalFPS / FPS; totalCoeff += coeff; return { elapsed: elapsed, coeff: goalFPS / FPS, FPS: FPS, averageFPS: totalFPS / iterCount, read more..

  • Page - 63

    moveAndDraw changeImage() animIndex animIndex animIndex2 changeImage() var bouncyBoss = function (numBouncy, $drawTarget) { var bouncys = [], timer = timeInfo(40); for (var i = 0; i < numBouncy; i++) { bouncys.push(bouncySprite({ images: '/images/cogs.png', imagesWidth: 256, read more..

  • Page - 64

    // IE6 background image caching fix. // Include this JavaScript at the top of your page. try { document.execCommand("BackgroundImageCache", false, true); } catch(e) {} 46 | Chapter 2: DHTML Essentials read more..

  • Page - 65

    CHAPTER 3 Scrolling CSS-Only Scrolling Effects div #extraDiv3 { position:fixed !important; position:absolute; bottom:0; left:0; width:100%; height:30% !important; height:110px; 47 read more..

  • Page - 66

    min-height:110px; max-height:318px; background:url('bas.png') no-repeat 50% 0%; z-index:4; } position:fixed div div 48 | Chapter 3: Scrolling read more..

  • Page - 67

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>CSS Parallax</title> <style type="text/css"> body { padding:0px; margin:0px; } .layer { read more..

  • Page - 68

    #back { background: #3BB9FF url(back1.png) 20% 0px; } #middle{ background: transparent url(back2.png) 30% 0px ; } #front{ background: transparent url(back3.png) 40% 0px; } </style> read more..

  • Page - 69

    back middle front position:absolute Scrolling with JavaScript Background Image Scrolling <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>CSS Parallax</title> <style type="text/css"> body { padding:0px; margin:0px; read more..

  • Page - 70

    .layer { position:absolute; height:256px; width:100%; } #back { background: #3BB9FF url(back1.png); } #middle{ background: transparent url(back2.png); } read more..

  • Page - 71

    // Apply it to the layers' background image positions, // scaled up for the front two layers so they move quicker // than the farthest layer. $back.css({ backgroundPosition: xPos + 'px 0px' read more..

  • Page - 72

    div image image div image div image div Snapping... axisSize tileWidth numTilesAxis = Math.ceil((axisSize + tileWidth) / tileWidth); 54 | Chapter 3: Scrolling read more..

  • Page - 73

    snapPos = -(scrollPosition % tileWidth); Scrolling with JavaScript | 55 read more..

  • Page - 74

    left top index = map[(yPos * mapWidth) + xPos]; ...and Wrapping Keeping things fast $ 56 | Chapter 3: Scrolling read more..

  • Page - 75

    '0px 0px' '0px 64px' left top Tile scrolling code tileScroller Property Description $viewport Viewport element in DOM tileWidth Width of tiles, in pixels tileHeight Height of tiles, in pixels wrapX Whether to wrap map horizontally wrapY Whether to wrap map vertically mapWidth Width of map, in tiles mapHeight Height of map, in tiles image URL of single tileset image that contains individual tile read more..

  • Page - 76

    // One instance of tileScroller is required for each viewport. var tileScroller = function (params) { var that = {}, $viewport = params.$viewport, // Calculate maximum number of tiles that can be displayed in viewport. tilesAcross = Math.ceil(($viewport.innerWidth() + params.tileWidth) / read more..

  • Page - 77

    // This is quicker than calculating when updating later. tileBackPos.push('0px 0px'); // Tile zero - special 'hidden' tile. for (top = 0; top < params.imageHeight; top += params.tileHeight) { for (left = 0; left < params.imageWidth; left += params.tileWidth) { tileBackPos.push(-left + 'px ' + -top + 'px'); read more..

  • Page - 78

    for (countDown = tilesDown; countDown; countDown--) { // Wrap vertically? if (wrapY) { if (sy >= mapHeight) { sy -= mapHeight; } } else read more..

  • Page - 79

    Creating tile maps with Tiled Scrolling with JavaScript | 61 read more..

  • Page - 80

    62 | Chapter 3: Scrolling read more..

  • Page - 81

    Scrolling with JavaScript | 63 read more..

  • Page - 82

    <?xml version="1.0" encoding="UTF-8" ?> <map version="1.0" orientation="orthogonal" width="32" height="16" tilewidth="64" tileheight="64"> <tileset firstgid="1" name="tiles2" tilewidth="64" tileheight="64"> <image source="tiles2.png" width="512" height="320" /> read more..

  • Page - 83

    loadMap() ajax() split() var val1 = '64', val2 = '64';// String values as stored in XML file. var total = val1 + val2; // = string '6464', not number 128. + var val1 = '64', val2 = '64';// Values as stored in XML file. var total = +val1 + +val2; // = number 128 as desired. var val1 = '64', val2 = '64';// Values as stored in XML file. var total = read more..

  • Page - 84

    $(xml).find('layer').each(function() { // Setup parameters to pass to tileScroller. // The + operator before some values is to ensure // they are treated as numerics instead of strings. var params = { read more..

  • Page - 85

    div loadMap() <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>JavaScript Tile Map Scrolling</title> <style type="text/css"> body { padding:0px; margin:0px; } #viewports { read more..

  • Page - 86

    // As mouse is moved around viewports, // calculate a speed to scroll by. $('#viewports').mousemove(function (ev) { xSpeed = ev.clientX - (viewWidth / 2); xSpeed /= (viewWidth / 2); xSpeed *= read more..

  • Page - 87

    CHAPTER 4 Advanced UI HTML5 Forms email tel url number range search color date week 69 read more..

  • Page - 88

    month time datetime datetime-local hidden text password <input type='date'> <input> 70 | Chapter 4: Advanced UI read more..

  • Page - 89

    Using JavaScript UI Libraries Using jQuery UI for Enhanced Web Interfaces Using JavaScript UI Libraries | 71 read more..

  • Page - 90

    Accordion Autocomplete Button Datepicker Dialog Progressbar Slider Tabs 72 | Chapter 4: Advanced UI read more..

  • Page - 91

    Draggable Droppable Resizable Selectable Sortable Loading and using jQuery UI <!DOCTYPE html> <html> <head> <title>jQuery UI</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- jQuery UI font sizes are relative to document's, so set a base size here. --> <style read more..

  • Page - 92

    type="text/css" media="all" /> <!-- Load jQuery. --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script> <!-- Load jQuery UI. --> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js" read more..

  • Page - 93

    Heavy Duty UI with Ext JS Using JavaScript UI Libraries | 75 read more..

  • Page - 94

    76 | Chapter 4: Advanced UI read more..

  • Page - 95

    Loading and using Ext JS <!DOCTYPE html> <html> <head> <title>Ext JS</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- Load the Ext JS CSS. --> <link rel="stylesheet" type="text/css" href="http://extjs.cachefly.net/ext-3.3.1/resources/css/ext-all.css" /> <!-- read more..

  • Page - 96

    fieldLabel: 'Date Widget', emptyText:'Enter date...', format:'Y-m-d', width: 128 }), // Create a Slider object. slider = new Ext.Slider({ read more..

  • Page - 97

    position: absolute setInterval() setTimeout() Creating a 3D Carousel Creating UI Elements from Scratch | 79 read more..

  • Page - 98

    80 | Chapter 4: Advanced UI read more..

  • Page - 99

    Carousel specifications alt carousel3d $('.carousel3d').Carousel(); Creating UI Elements from Scratch | 81 read more..

  • Page - 100

    Carousel image loading width height load load load image loadImage() new Image() loadImage() 82 | Chapter 4: Advanced UI read more..

  • Page - 101

    // Function to execute a callback when an image has been loaded, // either from the network or from the browser cache. var loadImage = function ($image, src, callback) { // Bind the load event BEFORE setting the src. $image.bind("load", function (evt) { // Image has loaded, so unbind event and call callback. read more..

  • Page - 102

    // A range used in the scale calculation to ensure // the frontmost item has a scale of 1, // and the farthest item has a scale as defined // in options.minScale. sizeRange = (1 - options.minScale) * 0.5, // An object to store the public update function. read more..

  • Page - 103

    loadImage($image, $image.attr('src'), function ($image) { loaded = true; // Save the image width and height for the scaling calculations. orgWidth = $image.width(); orgHeight = $image.height(); // Make the item fade-in. $image.animate({ opacity: 1 read more..

  • Page - 104

    // the front of the carousel. angle = Math.PI / 2, i; // Create a function that is called when the mouse moves over // or out of an item. $wrap.bind('mouseover mouseout', function (evt) { // Has the event been triggered on an image? Return if not. if read more..

  • Page - 105

    The jQuery plug-in part <div class="carousel" ><!-- This is the wrapping element --> <img src="pic1.png" alt="Pic 1"/> <img src="pic2.png" alt="Pic 2"/> <img src="pic3.png" alt="Pic 3"/> <img src="pic4.png" alt="Pic 4"/> <img src="pic5.png" alt="Pic 5"/> read more..

  • Page - 106

    // These are the default options. $.fn.Carousel.defaults = { radiusX:230, // Horizontal radius. radiusY:80, // Vertical radius. width:512, // Width of wrapping element. height:300, // Height of wrapping element. frameRate: 30, // Frame rate in milliseconds. rotRate: 5000, // Time it takes for carousel to read more..

  • Page - 107

    // the list of DOM elements that wrap groups of images. // These groups of images are turned into carousels. $.fn.Carousel = function(options) { /*** CODE REMOVED FOR CONCISENESS ***/ }; // These are the default options. $.fn.Carousel.defaults read more..

  • Page - 108

    90 | Chapter 4: Advanced UI read more..

  • Page - 109

    CHAPTER 5 Introduction to JavaScript Games 91 read more..

  • Page - 110

    DHTMLSprite timeInfo Game Objects Overview 92 | Chapter 5: Introduction to JavaScript Games read more..

  • Page - 111

    Game Objects Overview | 93 read more..

  • Page - 112

    The Game Code Game-Wide Variables $drawTarget div 94 | Chapter 5: Introduction to JavaScript Games read more..

  • Page - 113

    var PLAYER = 1, LASER = 2, ALIEN = 4, ALIEN_BOMB = 8, SHIELD = 16, SAUCER = 32, TOP_OF_SCREEN = 64, TANK_Y = 352 - 16, SHIELD_Y = TANK_Y - 56, SCREEN_WIDTH = 480, SCREEN_HEIGHT = 384, ALIEN_COLUMNS = 11, ALIEN_ROWS = 5, SYS_process, SYS_collisionManager, read more..

  • Page - 114

    Button Code Button Code Button Code Home 36 Left arrow 37 Up arrow 38 Right arrow 39 Down arrow 40 Insert 45 Delete 46 0 48 1 49 250 3 51 452 553 6 54 755 8 56 9 57 a 65 b66 c 67 d68 e 69 f 70 g 71 h 72 i 73 j 74 k 75 l 76 m 77 n 78 o 79 p 80 q 81 r 82 s 83 t 84 u 85 v 86 w 87 x 88 y 89 z 90 Left window 91 Right window 92 Select 93 Numeric pad 0 96 Numeric pad 1 97 Numeric pad read more..

  • Page - 115

    'fire': 0 }, key; keydown keyup document keyMap{} kInfo{} return false keyMap{} $(document).bind('keydown keyup', function (event) { key = '' + event.which; if (keyMap[key] !== undefined) { kInfo[keyMap[key]] = event.type === 'keydown' ? 1 : 0; read more..

  • Page - 116

    return { add: function (process) { addedItems.push(process); }, process() processList[] newProcessList[] processList[] newProcessList[] addedItems[] addedItems[] processList[] process: function () { var newProcessList = [], len = processList.length; read more..

  • Page - 117

    if (imageIndex === imageList.length) { imageIndex = 0; } that.draw(x, y); }; SYS_process.add(that); }; Collision Detection colliderFlag collideeFlags colliderFlag collideeFlags collideeFlags Laser Saucer Shield colliderFlag 12 4 collideeFlags 2 + 4 0 0 doCheck = objectA.collideeFlag & objectB.colliderFlag; read more..

  • Page - 118

    100 | Chapter 5: Introduction to JavaScript Games read more..

  • Page - 119

    SYS_collisionManager var collisionManager = function () { listIndex checkList check ListIndex checkList gridWidth gridHeight var listIndex = 0, grid = [], checkListIndex = 0, checkList = {}, gridWidth = 15, gridHeight = 12; listIndex for (var i = 0; i < gridWidth * gridHeight; i++) { read more..

  • Page - 120

    newCollider() colliderFlag collideeFlags return { newCollider: function(colliderFlag, collideeFlags, width, height, callback){ var list, indexStr = '' + listIndex++, checkIndex; var colliderObj = { halfWidth: width / 2, read more..

  • Page - 121

    checkCollisions() checkCollisions: function (offsetX, offsetY) { var list = getGridList(colliderObj.centerX + offsetX, colliderObj.centerY + offsetY); if (!list) { read more..

  • Page - 122

    if (checkList.hasOwnProperty(idx)) { colliderObj = checkList[idx]; for (var y = −32; y <= 32; y += 32) { for (var x = −32; x <= 32; x += 32) { read more..

  • Page - 123

    move() that.move = function () { y += 3.5 * SYS_timeInfo.coeff; that.draw(x, y); collider.update(x, y); if (y >= TANK_Y) { that.remove(); } }; SYS_process.add(that); }; Alien invaders aliensManager canFire false var alien = function (x, y, frame, read more..

  • Page - 124

    collisionWidth = 25; } collider = SYS_collisionManager.newCollider(ALIEN, 0, collisionWidth, 16, that.remove); collider.update(x, y); move() dx dy that.move = function (dx, dy) { that.changeImage(frame + animFlag); animFlag ^= 1; x += dx; y += dy; read more..

  • Page - 125

    return that; }; Aliens manager aliensManager aliensManager hitFunc() var aliensManager = function (gameCallback, startY) { var aliensList = [], aliensFireList = [], paused = false, moveIndex, dx = 4, dy = 0, images = [0, 2, 2, 4, 4], changeDir read more..

  • Page - 126

    aliensManager that that = { pause() pauseAliens: function (pauseTime) { paused = true; setTimeout(function () { paused = false; }, pauseTime); }, move() moveIndex aliensManger move: function () { read more..

  • Page - 127

    return; } canFire true aliensFireList if (anAlien.canFire) { aliensFireList.push(anAlien); } true changeDir var dx2 = dy ? 0 : dx; if (anAlien.move(dx2, dy)) { read more..

  • Page - 128

    }); aliensFireList = []; waitFire = true; } } } }; alienManager that SYS_process.add(that); return that; }; The Player Tank DHTMLSprite that var read more..

  • Page - 129

    that.draw(x, TANK_Y); collider.update(x, TANK_Y); canFire if (canFire) { if (keys.fire) { if (!waitFireRelease) { laser(x, TANK_Y+8, function(){canFire = true;} ); canFire = false; read more..

  • Page - 130

    Laser DHTMLSprite var laser = function (x, y, callback) { var that = DHTMLSprite(SYS_spriteParams); remove() that.remove = function (collideeFlags) { if (collideeFlags & (TOP_OF_SCREEN + SHIELD + ALIEN_BOMB)) { animEffect(x, y, [18], 250, null); } that.destroy(); read more..

  • Page - 131

    Shields var shield = function (x, y) { shieldBrick DHTMLsprite var shieldBrick = function (x, y, image) { var that = DHTMLSprite(SYS_spriteParams), collider, hit() hit = function () { that.destroy(); collider.remove(); read more..

  • Page - 132

    Mystery Saucer dx x var saucer = function (gameCallback) { var dx = (Math.floor(Math.random() * 2) * 2) - 1, x = 0; dx *= 1.25; if (dx < 0) { x = SCREEN_WIDTH - 32; } DHTMLSprite var that = DHTMLSprite(SYS_spriteParams); that.changeImage(20); remove() var remove = function () { read more..

  • Page - 133

    SYS_process.add(that); }; The Game game move() process collisionMan ager var game = function () { var time, aliens, gameState = 'titleScreen', aliensStartY, lives, score = 0, highScore = 0, extraLifeScore = 0, saucerTimeout = 0, read more..

  • Page - 134

    extraLifeScore += 5000; lives++; } if (!$('#score').length) { $("#draw-target").append('<div id="score"></div>' + '<div id="lives"></div><div read more..

  • Page - 135

    setTimeout(function () { $("#draw-target").children().remove(); $("#draw-target").append('<div class="message">' + '<p>*** GAME OVER ***</p></div>' + startText); gameState = 'titleScreen'; read more..

  • Page - 136

    aliensStartY += 32; } newWaveTimeout = setTimeout(function () { init(); }, 2000); break; case 'aliensAtBottom': read more..

  • Page - 137

    Putting It All Together draw-target <!DOCTYPE html> <html> <head> <title>Orbit Assualt</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <style type="text/css"> #draw-target { width:480px; height:384px; background-color:#000; position:relative; color:#FFF; read more..

  • Page - 138

    document.execCommand("BackgroundImageCache", false, true); } catch(err) {}; var PLAYER = 1, LASER = 2, ALIEN = 4, ALIEN_BOMB = 8, /*** CODE REMOVED FOR CONCISENESS ***/ }; read more..

  • Page - 139

    /*** CODE REMOVED FOR CONCISENESS ***/ }; var saucer = function (gameCallback) { /*** CODE REMOVED FOR CONCISENESS ***/ }; var game = function () { /*** CODE REMOVED FOR CONCISENESS ***/ }(); }); read more..

  • Page - 140

    read more..

  • Page - 141

    CHAPTER 6 HTML5 Canvas div 123 read more..

  • Page - 142

    <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <script> $(document).ready(function() { var a_canvas = read more..

  • Page - 143

    Canvas Limitations Canvas Versus SVG Canvas Versus SVG | 125 read more..

  • Page - 144

    <?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 width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect id='a_rectangle' width="300" height="100" style="fill:rgb(0,0,255)" /> </svg> a_rectangle Canvas read more..

  • Page - 145

    Canvas Exporters Canvas Exporters | 127 read more..

  • Page - 146

    128 | Chapter 6: HTML5 Canvas read more..

  • Page - 147

    Canvas Drawing Basics The Canvas Element <canvas id = 'mycanvas' width = 512 height = 384> Fallback content </canvas> width height width:50% id var canvas = document.getElementById('mycanvas'); // Or, using jQuery: var canvas = $('#mycanvas')[0]; The Drawing Context var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); Canvas Drawing Basics | 129 read more..

  • Page - 148

    ctx Drawing Rectangles // Draw a 100 by 150 pixel filled rectangle at coordinate (10,10). ctx.fillRect(10,10,100,150); // Draw a 100 by 150 pixel outlined rectangle at coordinate (10,10). ctx.strokeRect(10,10,100,150); // Clear a 100 by 150 pixel rectangle at coordinate (10,10). ctx.clearRect(10,10,100,150); Drawing Paths with Lines and Curves 130 | Chapter 6: HTML5 Canvas read more..

  • Page - 149

    Function Description beginPath() Starts a new path moveTo() Sets the current position of the path lineTo() Defines a line from the current position arc() Defines an arc (portions of a circle) arcTo() Defines an arc from the current position quadraticCurveTo() Defines a quadratic curve from the current position bezierCurveTo() Defines a Bézier curve from the current position closePath() Ends a path read more..

  • Page - 150

    arc() arc(x, y, radius, startAngle, endAngle, anticlockwise); x,y radius startAngle endAngle π anticlockwise var radians = degrees * Math.PI / 180; 132 | Chapter 6: HTML5 Canvas read more..

  • Page - 151

    var degrees = radians * 180 / Math.PI; endAngle var endAngle = 0.0; for (var x = 50; x < 500; x += 100) { ctx.beginPath(); ctx.moveTo(x, 190); endAngle += (2 * Math.PI) / 5; ctx.arc(x, 190, 50, 0, endAngle, false); ctx.fill(); } endAngle = 0.0; for (x = 50; x < 500; x += 100) { ctx.beginPath(); ctx.moveTo(x, 310); read more..

  • Page - 152

    w,h cr var drawRoundedRect = function (ctx, x, y, w, h, cr) { ctx.beginPath(); ctx.moveTo(x + w / 2, y); // Start in the middle of the top edge. ctx.arcTo(x + w, y, x + w, y + h, cr); // Top edge and upper-right corner. ctx.arcTo(x + w, y + h, x, y + h, cr); // Right edge and lower-right read more..

  • Page - 153

    }; var cr = 0; for (x = 0; x < 500; x += 100) { drawRoundedRect(ctx, x + 5, ctx.canvas.height / 2 - 45, 90, 90, cr); read more..

  • Page - 154

    $('.dragger').draggable({ cursor: 'crosshair' }); // Trapping the 'mousedown' event and returning false // prevents the text select caret from appearing. read more..

  • Page - 155

    <body style="position:relative;"> <div class="dragger" id="dragger1" style="background-color:#f00;"> </div> <div class="dragger" id="dragger2" style="background-color:#0f0;"> </div> <div class="dragger" id="dragger3" read more..

  • Page - 156

    Drawing Bitmap Images drawImage() Image() <img> <video> <video> drawImage() draw Image() 138 | Chapter 6: HTML5 Canvas read more..

  • Page - 157

    drawImage() drawImage(source, x, y); drawImage(source, x, y, width, height); Canvas Drawing Basics | 139 read more..

  • Page - 158

    drawImage(source, sx, sy, swidth, sheight, x, y, width, height); draw Image() Math.floor(x) (x>>0) Colors, Strokes, and Fills stroke() lineWidth strokeStyle fill Style var drawRoundedRect = function (ctx, x, y, w, h, cr) { ctx.beginPath(); ctx.moveTo(x + w / 2, y); // Start in the middle of the top edge. ctx.arcTo(x + w, y, read more..

  • Page - 159

    globalAlpha globalAlpha globalAlpha globalAlpha globalAlpha globalAlpha ctx.fillStyle = 'red'; // HTML4 color name. ctx.fillStyle = '#f00'; // Hexadecimal RGB. ctx.fillStyle = '#ff0000'; // Hexadecimal RRGGBB. ctx.fillStyle = 'rgb(255, 0, 0); // read more..

  • Page - 160

    CanvasGradient addColorStop() cg.addColorStop(0, 'black'); cg.addColorStop(0.5, 'white'); cg.addColorStop(1, 'red'); var drawSkyAndGrass = function (ctx){ // The gradient line is defined from the top to the bottom of the canvas. var cg = ctx.createLinearGradient(0, 0, 0, ctx.canvas.height); // Start off with sky blue at the top. cg.addColorStop(0, '#00BFFF'); read more..

  • Page - 161

    ctx.fillRect(0, 0, ctx.canvas.width/2, ctx.canvas.height/2); CanvasGradient createRadialGradient() ctx.createRadialGradient(circle1x, circle1y, circle1Radius, circle2x, circle2y, circle2Radius); addColorStop() addColorStop() addColorStop() Canvas Drawing Basics | 143 read more..

  • Page - 162

    var drawSun = function(ctx) { // Create a radial gradient with a 32-pixel-radius inner circle // and a 64-pixel-radius outer circle. Both are positioned at (64,64). var radGrad = ctx.createRadialGradient(64, 64, 32, 64, 64, 64); // The inner circle is white and opaque. radGrad.addColorStop(0,'white'); // The outer circle is yellow read more..

  • Page - 163

    <title> Naive implementation of animation in Canvas. </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <script> read more..

  • Page - 164

    <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <script> $(function() { var a_canvas = $("#a_canvas")[0], read more..

  • Page - 165

    </canvas> </body></html> Canvas and Recursive Drawing var rescurse(value1, value2) { value1−−; value2++; if (value1 <= 0) return; recurse(value1, value2); }; recurse(10,0); var drawTree = function (ctx, startX, startY, length, angle, depth, branchWidth) { var rand = Math.random, newLength, newAngle, newDepth, read more..

  • Page - 166

    // If we are near the end branches, make them green to look like leaves. if (depth <= 2) { ctx.strokeStyle = 'rgb(0,' + (((rand() * 64) + 128) >> 0) + ',0)'; } // Otherwise, choose a random brownish color. else { ctx.strokeStyle = 'rgb(' + (((rand() * 64) + 64) >> 0) + ',50,25)'; read more..

  • Page - 167

    newAngle = angle + rand() * maxAngle - maxAngle * 0.5; newLength = length * (0.7 + rand() * 0.3); drawTree(ctx, endX, endY, newLength, newAngle, newDepth, branchWidth); } }; Canvas Tree Page Layout drawTree() depth <!DOCTYPE html> <html> <head> <title> read more..

  • Page - 168

    The New CanvasSprite Object CanvasSprite DHTMLSprite params ctx var CanvasSprite = function (params) { // The canvas drawing context is passed in the params object. var ctx = params.ctx, width = params.width, height = params.height, imagesWidth = params.imagesWidth, vOffset = 0, read more..

  • Page - 169

    Other Code Changes CanvasSprite var bouncySprite = function(params) { // Other code as before goes here... // We are now referencing CanvasSprite instead of DHTMLSprite. // that = DHTMLSprite(params); that = CanvasSprite(params); // Other code as before goes here... }; var bouncyBoss = function (numBouncy, $drawTarget, ctx) { var bouncys read more..

  • Page - 170

    The WebSockets Advantage 152 | Chapter 6: HTML5 Canvas read more..

  • Page - 171

    WebSockets Support and Security A Graphical Chat Application with Canvas and WebSockets | 153 read more..

  • Page - 172

    Turning on WebSockets in Firefox 4 and Opera 11 about:config network.websocket.override-security-block opera:config The Chat Application The socket server 154 | Chapter 6: HTML5 Canvas read more..

  • Page - 173

    WebSocketServer process() $ $ . + Installing a web hosting environment locally A Graphical Chat Application with Canvas and WebSockets | 155 read more..

  • Page - 174

    php path-to-socket-server\server.php 156 | Chapter 6: HTML5 Canvas read more..

  • Page - 175

    The camera camera setFOVandYPos() worldToScreen() screenToWorld() worldToScreen() screenToWorld() toFixed() A Graphical Chat Application with Canvas and WebSockets | 157 read more..

  • Page - 176

    var camera = function () { var camDist, camY; return { setFOVandYPos: function (angle, y) { camY = y; angle *= (Math.PI / 180); camDist = (ctx.canvas.width * 0.5) / Math.tan(angle * 0.5); }, worldToScreen: function (x, y, z) read more..

  • Page - 177

    gradient1.addColorStop(1.00, color); gradient2 = ctx.createRadialGradient(37.6, 15.3, 0.0, 37.6, 15.3, 31.1); gradient2.addColorStop(0.00, "#fff"); gradient2.addColorStop(1.00, color); that.remove = false; that.setDest = function (dstX, dstZ) { destX = dstX; destZ = dstZ; }; that.getZ = read more..

  • Page - 178

    ctx.stroke(); // Draw the head. ctx.beginPath(); ctx.moveTo(61.2, 25.3); ctx.bezierCurveTo(61.2, 38.4, 50.5, 49.1, 37.4, 49.1); ctx.bezierCurveTo(24.2, 49.1, 13.6, 38.4, 13.6, 25.3); ctx.bezierCurveTo(13.6, 12.1, 24.2, 1.5, 37.4, 1.5); ctx.bezierCurveTo(50.5, read more..

  • Page - 179

    tx, w, x1, y1, w1, i; ctx.font = "bold 14px sans-serif"; ctx.fillStyle = '#000'; for (i = textList.length - 1; i > −1; i--) { tx = textList[i]; w = ctx.measureText(tx.text).width / read more..

  • Page - 180

    Initialization initAndGo() var initAndGo = function () { // Set the field of view and camera vertical position. camera.setFOVandYPos(125, −128); // Socket server is running on the local machine on port 8999. var host = "ws://127.0.0.1:8999", socket, avatarList = []; // The send function transmits an arbitrary read more..

  • Page - 181

    } if (data[userId].chattext !== undefined) { // Add chat text if present in data. textScroller.addText(unescape(data[userId].chattext), read more..

  • Page - 182

    // to ensure consistent speed across different browsers and hardware. coeff = elapsed / 20; oldTime = newTime; // Draw the background. There is no need to erase // the canvas first, as the background completely fills it. drawBackground(); read more..

  • Page - 183

    var avatar = function (color) { /*** CODE REMOVED FOR CONCISENESS ***/ }; var drawBackground = function () { /*** CODE REMOVED FOR CONCISENESS ***/ }(); var initAndGo = read more..

  • Page - 184

    read more..

  • Page - 185

    CHAPTER 7 Vectors for Games and Simulations 167 read more..

  • Page - 186

    168 | Chapter 7: Vectors for Games and Simulations read more..

  • Page - 187

    lengthSquared = (x*x + y*y); Vectors for Games and Simulations | 169 read more..

  • Page - 188

    √ length = Math.sqrt(x*x + y*y); length = Math.sqrt(-3*-3 + 3*3); // length = 4.24. Operations on Vectors Addition and Subtraction 170 | Chapter 7: Vectors for Games and Simulations read more..

  • Page - 189

    Scaling Normalization Rotation π π Operations on Vectors | 171 read more..

  • Page - 190

    // Degrees to radians. degToRad = function(deg) { return deg * (Math.PI/180); }; // Radians to degrees. radToDeg = function(rad) { return rad * (180/Math.PI); }; Dot Product 172 | Chapter 7: Vectors for Games and Simulations read more..

  • Page - 191

    Creating a JavaScript Vector Object vx vy var vector2d = function (x, y) { var vec = { // x and y components of vector stored in vx,vy. vx: x, vy: y, // scale() method allows us to scale the vector // either up or down. scale: function (scale) { read more..

  • Page - 192

    // normalize() method turns the vector into a unit length vector // pointing in the same direction. normalize: function () { var len = Math.sqrt(vec.vx * vec.vx + vec.vy * vec.vy); if (len) { vec.vx /= len; read more..

  • Page - 193

    Simulation-Wide Variables var gameObjects = [], // An array of game objects. canvas = document.getElementById('canvas'), // A reference to the Canvas. ctx = canvas.getContext('2d'); // A reference to the drawing context. A Cannon Simulation Using Vectors | 175 read more..

  • Page - 194

    game Objects[] The Cannonball var cannonBall = function (x, y, vector) { var gravity = 0, that = { x: x, // Initial x position. y: y, // Initial y position. removeMe: read more..

  • Page - 195

    angle = Math.atan2(mouseY - cannonY, mouseX - cannonX); vector = vector2d(mouseX - cannonX, mouseY - cannonY); vec.normalize(); // Make it unit length. vec.scale(25); // Scale it up to 25 units. var cannon = function (x, y) { var mx = 0, my = 0, angle = 0, that = { x: read more..

  • Page - 196

    ctx.fill(); ctx.closePath(); ctx.restore(); } }; // When mouse is clicked, fire a cannonball. canvas.onmousedown = function (event) { // Create a vector from cannon postion in direction of mouse. read more..

  • Page - 197

    linGrad.addColorStop(0, '#00BFFF'); // Fade to white in the middle. linGrad.addColorStop(0.5, 'white'); // Green for the top of the grass. linGrad.addColorStop(0.5, '#55dd00'); // Fade to white at the bottom. linGrad.addColorStop(1, 'white'); // Use the CanvasGradient object as the fill style. ctx.fillStyle = read more..

  • Page - 198

    }; // Add an initial cannon to the game objects list. gameObjects.push(cannon(50,canvas.height-150)); // This is the main loop that moves and draws everything. setInterval( function() { drawSkyAndGrass(); // Here, we loop through all the object read more..

  • Page - 199

    The Game Object gameObject var gameObject = function (x, y, radius, mass) { var that = { x: x, y: y, vel: vector2d(0, 0), radius: radius, mass: mass, removeMe: false, move: function () { that.x += that.vel.vx; read more..

  • Page - 200

    that.y += canvas.height + 100; } else if (that.vel.vy > 0 && that.y > canvas.height + 50) { that.y −= canvas.height + 100; } }, draw: function () { return; } read more..

  • Page - 201

    var obstacle = function (x, y, radius) { var that = gameObject(x, y, radius, radius), randColor1 = Math.floor(Math.random()*0xffffff), randColor2 = ((randColor1 & 0xfefefe)>>1).toString(16); randColor1 = randColor1.toString(16); randColor1 = '#000000'.slice(0,7-randColor1.length) + randColor1; randColor2 = read more..

  • Page - 202

    var mx = 0, my = 0, // Initial angle and thrust vector are zero. angle = 0, thrust = vector2d(0, 0), // gameObject is initialized with radius of 15 and mass of 15. that = gameObject(x, y, 15, 15), // Keep a reference to the parent read more..

  • Page - 203

    ctx.beginPath(); ctx.moveTo(−1.0, 6.3); ctx.bezierCurveTo(−4.9, 6.3, −8.2, 3.2, −8.3, −0.7); ctx.bezierCurveTo(−8.4, −4.7, −5.2, −7.9, −1.2, −8.0); ctx.bezierCurveTo(−1.2, −8.0, −1.2, −8.0, −1.2, −8.0); ctx.bezierCurveTo(2.8, −8.1, 6.1, −4.9, 6.2, −1.0); read more..

  • Page - 204

    thrust.scale(0.1); // Scale it down. }; // When mouse is released, cancel thrust. canvas.onmouseup = function (event) { thrust = vector2d(0, 0); }; // Keep a note of the mouse position over the canvas. canvas.onmousemove = function (event) { var bb = read more..

  • Page - 205

    collideAll() var bounce = function(ball1,ball2) { var colnAngle = Math.atan2(ball1.y - ball2.y, ball1.x - ball2.x), length1 = ball1.vel.length(), length2 = ball2.vel.length(), dirAngle1 = Math.atan2(ball1.vel.vy, ball1.vel.vx), Rocket Simulation | 187 read more..

  • Page - 206

    dirAngle2 = Math.atan2(ball2.vel.vy, ball2.vel.vx), newVX1 = length1 * Math.cos(dirAngle1-colnAngle), newVX2 = length2 * Math.cos(dirAngle2-colnAngle); ball1.vel.vy = length1 * Math.sin(dirAngle1-colnAngle); ball2.vel.vy = length2 * Math.sin(dirAngle2-colnAngle); ball1.vel.vx =((ball1.mass-ball2.mass)*newVX1 + read more..

  • Page - 207

    Page Code <!DOCTYPE html> <html> <head> <script type="text/javascript" > window.onload = function() { var gameObjects = [], canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'); // Vector object. var vector2d = function (x, y) { read more..

  • Page - 208

    gameObjects.push(obstacle(x,y,radius)); } // This is the main loop that moves and draws everything. setInterval( function() { var gameObjectsFresh = []; drawBackground(); // Here, we loop through all the object in the read more..

  • Page - 209

    collide() length() lengthSquared() Rocket Simulation | 191 read more..

  • Page - 210

    read more..

  • Page - 211

    CHAPTER 8 Google Visualizations <img> src 193 read more..

  • Page - 212

    Limitations 194 | Chapter 8: Google Visualizations read more..

  • Page - 213

    Limitations | 195 read more..

  • Page - 214

    src <img> Chart Glossary 196 | Chapter 8: Google Visualizations read more..

  • Page - 215

    Day Cookie sales Cake sales Monday 90 75 Tuesday 40 65 Wednesday 60 35 Image Charts <html> <body> <img src = 'https://chart.googleapis.com/chart? cht=p3&chd=t:60,40&chs=500x250&chl=Hello|World'/> </body> </html> Image Charts | 197 read more..

  • Page - 216

    198 | Chapter 8: Google Visualizations read more..

  • Page - 217

    Data Formats and Chart Resolution Image Charts | 199 read more..

  • Page - 218

    scaledValue = resolution * dataValue / maxDataValue; maxDataValue maxDataValue maxData Value Basic text format chd=t:val_1_1,val_1_2,val_1_3|val_2_1,val_2_2,val_2_3|... 200 | Chapter 8: Google Visualizations read more..

  • Page - 219

    Text format with custom scaling chds chd=t:val_1_1,val_1_2,val_1_3|val_2_1,val_2_2,val_2_3|... chds=<series_1_min>,<series_1_max>,<series_2_min>,<series_2_max>,... Simple encoding format chd:s<series_1>,<series_2>,<series_n>,... chd=t:1,19,27,53,61,-1|12,39,57,45,51,27 chd=s:BTb19_,Mn5tzb var simpleEncode = function (valueArray, maxValue) { var simpleEncoding = read more..

  • Page - 220

    // fit within maxval. chartData += simpleEncoding.charAt( Math.round((simpleEncoding.length - 1) * currentValue / maxValue)); } else { // Invalid values will be ignored. chartData += '_'; } } return read more..

  • Page - 221

    extendedEncodingLen = extendedEncoding.length, exLenSquared = extendedEncodingLen * extendedEncodingLen, chartData = ''; for (var i = 0, len = valueArray.length; i < len; i++) { var numericVal = valueArray[i]; // Scale the value to fit within maxVal. var scaledVal = read more..

  • Page - 222

    for (var i = 0; i < 3; i++) { dataSet1.push(Math.random() * maxVal); dataSet2.push(Math.random() * maxVal); } // Create the URL using the random data sets. window.onload = function() { read more..

  • Page - 223

    // and labels for values (data set 1). 'chxl=0:|' + (100 - value) + '|1:|Good|Bad|Ugly&' + // Color and size of label text. read more..

  • Page - 224

    // Create the URL for QR bar codes. var URL = "https://chart.googleapis.com/chart?" + "chs=256x256&" + // Size. "cht=qr&" read more..

  • Page - 225

    Summary Interactive Charts <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <html> <head> <!-- Load the general Google AJAX API --> <script type="text/javascript" src="https://www.google.com/jsapi"> </script> <script read more..

  • Page - 226

    // Define a function to draw the chart. var drawChart = function() { // Create a data table (initially empty). var data = new google.visualization.DataTable(); // Define the columns in the table. read more..

  • Page - 227

    <iframe> var data = new google.visualization.Data Table() Interactive Charts | 209 read more..

  • Page - 228

    data.addColumn(type, label) type label data.addRows (numRows) numRows numRows data.addRows( [['Monday', 90, 75], ['Tuesday', 40, 65], ['Wednesday', 60, 35]]); data.setValue(row, column, value) value 210 | Chapter 8: Google Visualizations read more..

  • Page - 229

    var chart = new google.visualization.ColumnChart(chartElement) chartElement <div> chart.draw(data, options) options width height Interactive Charts Events Event name Description Values passed back error Triggered when an error occurs drawing the chart. id, message onmouse over Triggered when the mouse moves over a bar. row, column onmouse out Triggered when the mouse leaves a bar. row, column ready read more..

  • Page - 230

    Event name Description Values passed back select Triggered when a bar or legend is clicked. In the case of bars, both the row and column values will be set. They can then be used to identify the correct value in the data table. In the case of legends, only the column will be set. none Retrieving event information select getSelection() // onmouseover events pass values back to read more..

  • Page - 231

    var drawChart = function() { // Create a data table (initially empty). var data = new google.visualization.DataTable(); // Define the columns in the table. data.addColumn('string', 'Day'); read more..

  • Page - 232

    // This event listener shows various details about // the cell/column being clicked. // Columns are selected by clicking the legends. google.visualization.events.addListener(chart, 'select', function(){ read more..

  • Page - 233

    CHAPTER 9 Reaching the Small Screen with jQuery Mobile 215 read more..

  • Page - 234

    jQuery Mobile 216 | Chapter 9: Reaching the Small Screen with jQuery Mobile read more..

  • Page - 235

    data- <a href="#" data-role="button" data-icon="delete">Delete</a> data- value = $('#myelement).attr('data-mydata'); // value = contents of data-mydata. data- <div id='myelement' data-mydata = '99' ></div> data- data- data- data-myuniqueid-icon data-icon data- <!DOCTYPE html> jQuery Mobile | 217 read more..

  • Page - 236

    TilePic: A Mobile-Friendly Web Application TilePic Game Description 218 | Chapter 9: Reaching the Small Screen with jQuery Mobile read more..

  • Page - 237

    TilePic: A Mobile-Friendly Web Application | 219 read more..

  • Page - 238

    TilePic Game Code Application-wide variables var tileSize, // Tile size in pixels. numTiles, // Number of tiles, e.g. 4 = 4 by 4 grid. tilesArray, // An array of tile objects. emptyGx, // X position of empty tile space. emptyGy, // Y position of empty tile space. imageUrl; // Url of image to tile. 220 read more..

  • Page - 239

    The tile object tileObj $element gx gy solvedGx solvedGy move() animate() left top checkSolved() data() // tileObj represents a single tile in the puzzle. // gx and gy are the grid position of the tile. var tileObj = function (gx, gy) { // solvedGx and solvedGy are the grid coordinates // of the tile in its 'solved' position. var solvedGx = gx, read more..

  • Page - 240

    // is in the correct 'solved' position. checkSolved: function () { if (that.gx !== solvedGx || that.gy !== solvedGy) { return false; } return true; read more..

  • Page - 241

    dir dir = 1 x dir x = 1 dir x dir TilePic: A Mobile-Friendly Web Application | 223 read more..

  • Page - 242

    // When a tile is clicked on, the moveTiles() function will // move one or more tiles into the empty space. This can be done // with or without animation. var moveTiles = function (tile, animate) { var clickPos, x, y, dir, t; // If empty space is on same vertical level as clicked tile, // move tile(s) horizontally. if (tile.gy === read more..

  • Page - 243

    shuffle() TilePic setup code setup() // Initial setup. Clears picture frame of old tiles, // creates new tiles, and shuffles them. var setup = function () { var x, y, i; imageUrl = $("input[name='pic-choice']:checked").val(); // Create a subtle watermark 'guide' image to make the puzzle // a little easier. $('#pic-guide').css({ read more..

  • Page - 244

    TilePic events bindEvents() tap tap tileObj data() moveTiles() checkSolved() bindEvents() setup() var bindEvents = function () { // Trap 'tap' events on the picture frame. $('#pic-frame').bind('tap',function(evt) { var $targ = $(evt.target); // Has a tile been tapped? if (!$targ.hasClass('tile')) return; // If read more..

  • Page - 245

    }; // The checkSolved() function iterates through all the tile objects // and checks if all the tiles in the puzzle are solved. var checkSolved = function () { /*** CODE REMOVE FOR CONCISENESS ***/ }; read more..

  • Page - 246

    #pic-guide { position:absolute; backround-repeat:no-repeat; width:100%; height:100%; } .tile { border:1px solid; position:absolute; } #well-done read more..

  • Page - 247

    </fieldset> </div> <div data-role="fieldcontain"> <label for="difficulty" " class="select ">Choose Difficulty:</label> <select name="difficulty "" id="difficulty"> read more..

  • Page - 248

    PhoneGap 230 | Chapter 9: Reaching the Small Screen with jQuery Mobile read more..

  • Page - 249

    CHAPTER 10 Creating Android Apps with PhoneGap 231 read more..

  • Page - 250

    Installing PhoneGap Installing the Java JDK 232 | Chapter 10: Creating Android Apps with PhoneGap read more..

  • Page - 251

    Installing the Android SDK Installing PhoneGap | 233 read more..

  • Page - 252

    Installing Eclipse 234 | Chapter 10: Creating Android Apps with PhoneGap read more..

  • Page - 253

    Installing Android Development Tools Installing PhoneGap | 235 read more..

  • Page - 254

    ADT Plugin Installing PhoneGap Creating a PhoneGap Project in Eclipse 236 | Chapter 10: Creating Android Apps with PhoneGap read more..

  • Page - 255

    Creating a PhoneGap Project in Eclipse | 237 read more..

  • Page - 256

    Altering the App.java File package com.phonegap.tilepic; import android.app.Activity; import android.os.Bundle; import com.phonegap.*; public class App extends DroidGap { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); read more..

  • Page - 257

    Altering the AndroidManifest.xml File <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.phonegap.helloworld" android:versionCode="1" android:versionName="1.0"> <supports-screens android:largeScreens="true" android:normalScreens="true" read more..

  • Page - 258

    android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission read more..

  • Page - 259

    <!DOCTYPE HTML> <html> <head> <title>TilePic Test</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> </head> <body> <h1>TilePic Test</h1> </body> </html> Testing the TilePic Application Creating a PhoneGap Project in Eclipse | 241 read more..

  • Page - 260

    242 | Chapter 10: Creating Android Apps with PhoneGap read more..

  • Page - 261

    Index Symbols A 243 read more..

  • Page - 262

    B 244 | Index read more..

  • Page - 263

    C Index | 245 read more..

  • Page - 264

    246 | Index read more..

  • Page - 265

    D Index | 247 read more..

  • Page - 266

    E 248 | Index read more..

  • Page - 267

    F G Index | 249 read more..

  • Page - 268

    H 250 | Index read more..

  • Page - 269

    I J Index | 251 read more..

  • Page - 270

    K L M 252 | Index read more..

  • Page - 271

    N O Index | 253 read more..

  • Page - 272

    P 254 | Index read more..

  • Page - 273

    Q R S Index | 255 read more..

  • Page - 274

    256 | Index read more..

  • Page - 275

    T Index | 257 read more..

  • Page - 276

    U V 258 | Index read more..

  • Page - 277

    W Index | 259 read more..

  • Page - 278

    X Z 260 | Index read more..

  • Page - 279

    About the Author Colophon read more..

  • Page - 280

    read more..

Write Your Review