Multimedia – FWD 142 HTML5 Graphics PDF

Document Details

Applied College

Tags

html multimedia programming web development

Summary

This document is a course outline for a multimedia course, including an introduction to HTML5, multimedia, graphics, animations, and game programming. The document also highlights multimedia concepts and course content with a required textbook.

Full Transcript

Multimedia – FWD 142 Applied College  Course description  Chapter 1: Introduction to HTML5  Basic syntax  Links, structure and layout  Tables  Web forms Introduction to HTML5 2  This course covers the basic html5 multimedia concepts. This includes introdu...

Multimedia – FWD 142 Applied College  Course description  Chapter 1: Introduction to HTML5  Basic syntax  Links, structure and layout  Tables  Web forms Introduction to HTML5 2  This course covers the basic html5 multimedia concepts. This includes introduction to html5, html5 multimedia, html5 graphics, html5 animations, advanced html5 multimedia, and game programming with html5.  Course content  Introduction to HTML5  HTML5 multimedia  HTML5 graphics  HTML5 animations  Advanced HTML5 Multimedia  Game Programming with HTML5  Required TextBook  Earle Castledine. HTML5 Games: Novice to Ninja: Create Smash Hit Games in HTML5. SitePoint. 1st ed. 2018. Introduction to HTML5 3 Chapter 1: Introduction to HTML5 Applied College  Understand the principles of Web programming with HTML5.  Understand how HTML5 tags work and how to use them in the general makeup of an HTML document.  Learn HTML5 syntax, and how to write tags.  Enumerate and use HTML5 basic elements, to create a well-formatted, readable, and meaningful web page. Introduction to HTML5 5 6 The most basic building block of the Web. It defines the meaning and structure of web content. Other technologies besides HTML are generally used to describe a web page's appearance/presentation (CSS) or functionality/behaviour (JavaScript). Introduction to HTML5 https://www.w3schools.com/html/html_intro.asp 7 Introduction to HTML5  HTML stands for HyperText Markup Language and it does two important things:  Describes how webpages should look.  Defines the semantics of those pages.  HTML describes the structure of a Web page and consists of a series of elements, also called tags.  HTML elements label pieces of content such as "this is a heading", "this is a paragraph", "this is a link", etc.  An HTML file is simply a text file marked up with special codes that tell the web browser how to display the content. Introduction to HTML5 8 Introduction to HTML5 9 10 In this section: HTML tags, Comments, Structure of a HTML page, Semantic markup Introduction to HTML5  HTML is a set of text tags. These tags are inserted into the content of the HTML files that create your webpages, and they define the type of content being displayed in the browser. Introduction to HTML5 11 Introduction to HTML5 12  There’s one more key piece of text we might find in HTML tags: attributes.  Attributes provide additional information about the element they’re being applied to. Introduction to HTML5 13  Two notes about attributes:  Elements can have any number of attributes.  Some elements, like images () or hyperlinks (), require specific attributes to work properly.  Example of HTML element with three attributes: to define the destination of the link.  3. Type the link text (e.g., Visit Google) to provide a label for the user to click.  4. Type to finish the link  5. Save the file and view it in your browser Introduction to HTML5 37 Types of Links in HTML Links to other Links to different Links to specific websites external Links to other pages in a section of a page from our own applications webpage (internal) (external) Introduction to HTML5 38  Internal links are links to pages within the same website (or on the same domain).  External links are links to someone else’s webpage.  External links are always absolute. That is, they need to include the entire URL, including the protocol. If one of those items is missing or incomplete, the link will not work.  When linking internally, we don’t always need to include the entire URL, because it’s implied. This is the result of the difference between absolute and relative links. Introduction to HTML5 39  With an absolute link, we can include the entire URL in the anchor element markup. Introduction to HTML5 40  With an absolute link, we include the entire URL in the anchor element markup. Always use an absolute link when linking to an external site, but we will usually use relative links for files on your own site.  For example, when linking to a specific file called cart.html on the website mysite.com. We will need to know the location of the file in the site’s directory structure to link to it.  If cart.html is in a top-level folder (i.e., a folder in the root directory) called /store/, then the absolute link for this file is https://mysite.com/store/cart.html.  Relative links, on the other hand, don’t include the complete URL of the location we are linking to.  The structure of the link markup is based only on where the linked file is relative to the current file. So relative links are commonly used to link within pages on a single website, whose files share one common directory. Introduction to HTML5 41  Absolute URLs W3C Google  Relative URLs HTML Images CSS Tutorial Consider the following link: HTML tutorial  Link to a page located in the html folder on the current web site: HTML tutorial  Link to a page located in the same folder as the current page: HTML tutorial Introduction to HTML5 42 Introduction to HTML5 43  HTML links can be used to create bookmarks, so that readers can jump to specific parts of a web page.  Bookmarks can be useful if a web page is very long.  Linking to a specific section of the page is a great way to highlight specific content or drive a user to a pertinent area. 1. Assign a unique name to the section to which we are linking to, by including the id attribute. Contact Me! 2. Link to that id in the anchor tag: Jump to Contact Form Introduction to HTML5 44  Example of linking to a specific section of the page: Introduction to HTML5 45  There is a growing set of Uniform Resource Identifiers (URIs) that tell the browser which specific applications a link should open in.  While email links are the most common, we can also specify telephone numbers (tel:), file servers (ftp:), and more.  Email links are links that will open an email app on the device, with the email address (and potentially other information) filled in. To create an email link, the link is structured as follows: Email Joe Introduction to HTML5 46  By default, the linked page will be displayed in the current browser window. To change this, we must specify another target for the link.  The target attribute specifies where to open the linked document.  Several link targets can be used in HTML:  _blank opens the link in a new window.  _self opens the link in the same window (the default). current page was opened in a new window, this type of target allows opening  _parent: If the subsequent links in the original window.  _top opens the page in the full body of the window (useful if using the element).  An is a way to embed the content of one page into another. That is for example used when embeding a YouTube video on a page. framename opens the page in a specific. Introduction to HTML5 47 48 In this section: Webpage Layout, Block vs. Inline Elements, Page Sections, Building a Blog Article Layout. Introduction to HTML5  Aside from formatting text, HTML gives us a set of tools for defining areas of a webpage.  While they don’t affect the way a page looks (that’s what CSS is for), it’s yet another way to apply semantic meaning to webpages for users.  the items on a page are grouped into areas with specific functions, such as a header, a footer, a main area (which can contain several elements), and a sidebar.  Each of these boxes is an area defined in HTML and styled with CSS. But the browser knows how to arrange the areas thanks to Figure. The layout for the New York Times home page the HTML elements used to define them. Introduction to HTML5 49  Block elements take up the full available width, thus creating their own block on a page. Style-wise, each element fits into the box model and has its own spacing.  Two commonly used block elements are: and.  A paragraph is a block element.  Example: Hello World Hello World Introduction to HTML5 50  Inline elements take up only the width they need. Looking at this stylistically, by default there is no spacing applied directly to inline elements. , , and are all inline elements.  An inline element does not start on a new line.  Example:  Hello World Introduction to HTML5 51  A good way to get an idea of a page’s design and layout is to sketch out a wireframe. A wireframe is a blueprint or a general framework of a webpage.  Its focus is on content priority and lacks the niceties of visual design, like text styling or colors.  A wireframe indicates where content and elements are placed. Figure. A wireframe of a webpage that uses common page sections Introduction to HTML5 52  The header is the area that contains information at the top of a webpage or section of a webpage. A site’s header generally includes the site title and maybe a tagline or logo. Other elements, like articles, can also have a header tag, which might include the title, date, and author’s name. The navigation is also usually found in the header. The tag for this element is.  The navigation includes links to other important pages on the site. On a micro level, groups of pages or articles can have their own navigation (if an article is spread across several pages, for example). Its tag is.  The footer is at the bottom of the page or section of a page and is generally used to provide extra information. For a section of a page, it could display the date it was published or tags or keywords. For the entire site, the footer can include additional links, copyrights, or other legal disclosures. Its tag is. Introduction to HTML5 53  With the more general areas of a website covered, the content may change with each page.  A section (tag: ) is any discrete area of a website with related content. For example, on a home page there might be an “about me” section, an “articles” section, and a “photo gallery” section.  An article (tag: ) is an area that is often self-contained and can stand on its own (and is often related to syndication). Blog posts or a page’s main copy are usually described as articles.  An aside (tag: ) is auxiliary information that’s related to, but not integral to, the main content. Asides are often described as “sidebars,” but they don’t need to be physically to the side of the content. The tips in a web page can be considered asides.  To match the aside tag, there’s also a tag, which would denote the main content of the page. This will likely be a wrapper for articles or sections. Introduction to HTML5 54 About  To create a sidebar: Services Clients 1. Type. Contact 2. Type the heading Related Articles. 3. Created an unordered list of articles. Type. 4. Add the first item: type Wait until you see CSS. 5. Add as many related articles as we’d like. 6. Type. 7. Type to close the aside element. 8. Type to close the wrapper div. Introduction to HTML5 55  To create a site footer: 1. Type. 2. Add one paragraph for the copyright line. Type Copyright 3. [AUTHOR NAME]. 4. Type. Example of a footer section in a document: Author: Haithem Mezni [email protected] Introduction to HTML5 56 Tables A table represents information in a grid format. Examples of tables include financial reports, TV schedules, and sports results. Grids allow us to understand complex data by referencing information on two axes. Each block in the grid is referred to as a table cell. In HTML a table is written out row by row. HTML tables allow web developers to arrange data into rows and columns. Company Contact Country Alfreds Futterkiste Maria Anders Germany Centro comercial Moctezuma Francisco Chang Mexico  : This is the parent element. All the data in the table will be wrapped in the opening and closing table tags.  : Specifies a title or caption for the table. If included, this should be the first child element of the table.  : This stands for “table header” and will contain the column headings.  : Stands for “table body” and contains the primary content (or data) of the table.  : Short for “table row.” Each row of data goes in between opening and close tr tags.  : This is a cell of data (td stands for “table data”).  : If contained inside , th (table heading) can replace td as the table cell. Data tagged with will usually appear in bold by default.  : The “table footer,” this contains the table’s footer  Each table row starts with a and end with a tag. tr stands for table row. Each row may contain several data elements. and a tag. td stands for table data.  Each table cell is defined by a Everything between and are the content of the table cell.  Table data elements are the data containers of the table. They can contain all sorts of HTML elements; text, images, lists, other tables, etc. Emil Tobias Linus  Table Caption: We can add a caption that serves as a heading for the entire table.  To add a caption to a table, use the tag Monthly savings Month Savings January $100 February $50  HTML tables can have cells that spans over multiple rows and/or columns. Colspan. To make a cell span over multiple Rowspan. To make a cell span over columns, use the colspan attribute. The value of the multiple rows, use the rowspan attribute. The colspan attribute represents the number of columns to value of the rowspan attribute represents the span. number of rows to span. Name Phone Age 555-1234 64 In this section: Form components and attributes. Introduction to HTML5 - Web Forms  An HTML form is used to collect user input. The user input is most often sent to a server for processing.  Examples of web forms:  Contact forms  Comments Forums  Login boxes  Post boxes (on social media websites)  Search boxes  Checkout pages,  Add To Cart buttons, and payment submissions for online stores.  Etc. Introduction to HTML5 - Web Forms 65  Every form is wrapped in a element, which is used to represent a user’s input. form elements  The element is a container for different types of input elements, such as: text fields, checkboxes, radio buttons, submit buttons, etc. Introduction to HTML5 - Web Forms 66  HTML forms are described with additional attributes, such as the type and address of submission. Attribute Description accept-charset Specifies the charset used in the submitted form (default: the page charset). action Specifies an address (url) where to submit the form (default: the submitting page). autocomplete Specifies if the browser should autocomplete the form (default: on). enctype Specifies the encoding of the submitted data (default: is url-encoded). method Specifies the HTTP method used when submitting the form (default: GET). name Specifies a name used to identify the form (for DOM usage: document.forms.name). novalidate Specifies that the browser should not validate the form. target Specifies the target of the address in the action attribute (default: _self). Introduction to HTML5 - Web Forms 67  An HTML element, with all possible attributes set, will look like this: form elements (labels, text fields, select boxes, buttons, etc.) Introduction to HTML5 - Web Forms 68 The action attribute:  The action attribute defines the action to be performed when the form is submitted.  The common way to submit a form to a server, is by using a submit button. The form is submitted to a web page on a web server.  In the following example, a server-side script ("action_page.php") is specified to handle the submitted form:   If the action attribute is omitted, the action is set to the current page. Introduction to HTML5 - Web Forms 69 The method attribute:  This attribute specifies the HTTP method (GET or POST) to be used when submitting the forms:  default method  We can use GET if the form submission is passive (like a search engine query), and without sensitive information.  When we use GET, the form data will be visible in the page address:  action_page.php?firstname=Mickey&lastname=Mouse  POST is used if the form is updating data, or includes sensitive information (e.g., password).  POST offers better security because the submitted data is not visible in the page address. Introduction to HTML5 - Web Forms 70 71 In this section: Input elements, restrictions and attributes. Introduction to HTML5 - Web Forms  The element has the form of a Drop-Down list.  The element defines a drop-down list:  Example: Volvo Saab Fiat Audi Introduction to HTML5 - Web Forms 72  The defines a single-line input field for text input.  Example: First name: Last name: Introduction to HTML5 - Web Forms 73  The element defines a multi-line input field (a text area):  Example: HTML stands for HyperText Markup Language Introduction to HTML5 - Web Forms 74  The element defines a clickable button.  Example: Click Me! Introduction to HTML5 - Web Forms 75  defines a button for submitting a form to a form-handler.  The form-handler is typically a server page with a script for processing input data.  The form-handler is specified in the form's action attribute.  Example: First name: Last name: Introduction to HTML5 - Web Forms 76  The element groups related data in a form.  The element defines a caption for the element.  Example: Personal information: First name: Last name: Introduction to HTML5 - Web Forms 77  defines a password field.  Example: User name: Password: Introduction to HTML5 - Web Forms 78  The is used for input fields that should contain a numeric value.  We can set restrictions on the numbers. Depending on browser support, the restrictions can apply to the input field.  Example: Rating (between 1 and 5): Firefox Introduction to HTML5 - Web Forms 88  defines a radio button.  Radio buttons let a user select ONLY ONE of a limited number of choices.  Example: Male Female Introduction to HTML5 - Web Forms 89  defines a multiple-choices element, i.e., checkbox.  Checkboxes let a user select ZERO or MORE options of a limited number of choices.  Example: Language skills: English Spanish German French Introduction to HTML5 - Web Forms 90 91 In this section: Date, Color, Range, Search, Email, etc. Introduction to HTML5 - Web Forms  The is used for input fields that should contain a date.  Depending on browser support, a date picker can show up in the input field.  Example: Workshop date:  Example: Enter a date before 1980-01-01: Enter a date after 2000-01-01: Introduction to HTML5 - Web Forms 92  The allows the user to select a month and year. Depending on browser support, a date picker can show up in the input field.  Example: Expires end of (month and year):  The allows the user to select a week and year. Depending on browser support, a date picker can show up in the input field.  Example: Select a week: Introduction to HTML5 - Web Forms 93  The allows the user to select a time (no time zone).  Depending on browser support, a time picker can show up in the input field.  Example: Select a time: Introduction to HTML5 - Web Forms 94  The allows the user to select a date and time (no time zone). Depending on the browser support, a date picker can show up in the input field.  Example: Arrival (date and time):. 5. On the next line, type. Introduction to HTML5 - Web Forms 124 Introduction to HTML5 - Web Forms 125 Introduction to HTML5 - Web Forms 126 Multimedia – FWD 142 Chapter 2: HTML5 Multimedia Applied College Chapter goals ▪ Understanding media, as non-plain-text files. ▪ Learn how to add HTML5 audio and video elements to a web page. ▪ Learn how to use media elements in HTML5 games. HTML5 multimedia 2 Content ▪ Background on HTML media ▪ HTML5 media elements ▪ Accessing media elements with javascript ▪ Audio in HTML5 games ▪ Practice: Event and Background sounds in a game HTML5 multimedia 3 4 Background on HTML media HTML5 multimedia What is media? ▪ Media refers to any non-plain-text file. ▪ Examples include images, videos, and audios. ▪ A first step to use media on a Web page, is to store the media files on a web server and insert links to them into the HTML files. ▪ The browser will know how to open most common forms of media. ▪ When web developers talk about embedding video and audio files in webpages, they generally refer to a file’s format to distinguish one kind of file from another. ▪ What distinguishes one kind of media file from another is a complex mix of technical parameters, which can be broken down into file type, codec, and format: HTML5 multimedia 5 What is media? ▪ File type: Also called a file container, this is the way that the video or audio data is packaged into a file that a computer can read. ▪ Anything with a file extension is a file type, like.MOV,.MP4, etc. ▪ Each of these file types can contain video or audio data stored in one of several different ways (or even other kinds of data, like image data, subtitles, etc.). ▪ These file types are often called “formats,” even though the video in one.MP4 file, for example, might be of a very different type from the video in another.MP4 file. ▪ Codec: Recording video or audio data directly from a camera or a microphone produces truly vast amounts of digital data. To make this data more manageable, it’s almost always compressed for storage, then decompressed when it’s needed for editing or playback. ▪ The media industry uses numerous standards for this process; these are known as codecs short for “compressor/decompressor.”. ▪ You can think of the codec as the “language” in which the video or audio data is stored. H.264 is a very common video codec, and MP3 is an audio codec. ▪ Format: This refers to the internal structure of the media data. ▪ For video, this includes frame size, framerate, and pixel aspect ratio. ▪ Features of audio formats include the number of channels and configuration of those channels HTML5 multimedia 6 (whether stereo, multiple- mono, 5.1surround-sound, etc.). Embedding media files ▪ Embedding media consists in display it directly on the page, without having to open separate windows or applications. The media can be viewed, watched, or listened to without the user leaving the page. ▪ When we embed video or audio in the webpage, take care to choose files in formats that the most common browsers support. ▪ The best solution for video is usually to choose MP4, because all browsers support it, with some exceptions. Other supported formats include WebM and Ogg. ▪ Embedding audio in the webpage: we need to be mindful of the formats that are supported. WAV is supported by all browsers except Internet Explorer. The MP3 format is supported by all browsers. HTML5 multimedia 7 Embedding video ▪ We can embed a video on the webpage with the element. ▪ There are a few attributes to know as well: width, height, and controls. The “controls” attribute has no value, but adding it tells the browser to include the play, pause, and volume buttons. ▪ Between the opening and closing tags, we need to include the video source. Multiple video sources (which can use different formats) can be added, and the browser will pick the best one. HTML5 multimedia 8 Storing media files ▪ Multimedia—audio and video—will use considerable resources and bandwidth that the web server is likely not specialized for. This can lead to the website crashing or quickly running out of storage and bandwidth. ▪ Solution: use of specialized services to host the media, and then embed links to those services into the website using the embed code provided by the service. A YouTube video embedded on a webpage HTML5 multimedia The YouTube share dialog 9 10 HTML5 media elements HTML5 multimedia HTML5 media elements ▪ The media elements, audio and video, are a way of embedding playable media files directly into a web page without having to use Flash or a plug-in. The elements can be styled with CSS, integrated with SVG and Canvas, and controlled with JavaScript. ▪ Audio files are containers wrapping one type of media data, the audio stream, but video files typically wrap two different media streams: the video and the audio data streams. ▪ The audio and video elements both support a common syntax and subgroup of attributes. The only difference between the two elements is the content they manage, and a small group of additional attributes for the video element. HTML5 multimedia 11 Minimal element syntax ▪ In the HTML, an audio element is used to embed an audio file encoded as Ogg Vorbis into the web page. ▪ Ogg Vorbis is a fully open, non-proprietary, patent-and-royalty-free, general-purpose compressed audio format for mid to high quality ▪ The URL for the audio file is given in the audio element’s src attribute. HTML5 multimedia 12 Minimal element syntax ▪ Unlike the audio element, the video element has a play area that should show as long as there’s no error loading the video, and the video element isn’t deliberately hidden. ▪ To see the audio file in the page, we need to add the boolean controls attribute. ▪ Both the video and audio elements support the “controls” attribute for adding a default control UI (user interface) for the media resource. HTML5 multimedia 13 Alternative media ▪ Both the video and audio elements can contain zero or more source elements. ▪ These child elements define a way to specify more than one audio or video file in different formats. ▪ If a browser doesn’t support one format, it will find a format it supports in another source element. ▪ Example 1: The web page contains a video element, but rather than provide the location of the video file in the element’s src attribute, three different video files are defined in three different source child elements. HTML5 multimedia 14 Alternative media ▪ Example 2: A web page containing ▪ an embedded video element with three separate video types and ▪ fallback content for browsers that don’t support HTML5 video HTML5 multimedia 15 Media attributes Attribute Description Accesskey A unique, ordered, and space separated (as well as case sensitive) set of tokens that enables specifically named keyboard key access to the media element. class A set of space separated tokens specifying the various classes the element belongs to. contenteditable If true, content can be edited; if false, content cannot be edited. Contextmenu The id of the context menu associated with the element. dir The directionality of the element’s text. draggable Whether the media element can be dragged. If true, the element can be dragged; if false, the element cannot be dragged. dropzone What happens when an item is dropped on the element. HTML5 multimedia 16 Media attributes Attribute Description hidden A boolean attribute that determines if the element is “relevant”. Elements that are hidden are not rendered. id A unique identifier for the element. lang Specifies the primary language of the element’s contents. Tabindex Determines if media element is focusable, and the element’s order is in the tabbing sequence. title Advisory information, such as a tooltip. HTML5 multimedia 17 Media-Specific Attributes Attribute Description preload The preload attribute provides hints to the user agent about preloading the media content. autoplay The autoplay attribute is a boolean attribute whose presence signals the user agent to begin playing the media file as soon as it has loaded enough of the media file so that it can play through it without stopping. loop The loop attribute resets the media file back to the beginning when finished, and continues the play. muted If the muted attribute is present, the media plays, but without sound. HTML5 multimedia 18 Example of attributes usage ▪ The combination of loop and autoplay can be used to create a background sound for when a page is loaded, and continues to play until the user leaves the page. ▪ These attributes can be used with an audio element that doesn’t have a controls attribute, and is also hidden using CSS. ▪ Example of repeating auto-started audio in two formats to ensure browser coverage: HTML5 multimedia 19 20 Accessing media with javascript HTML5 multimedia Audio and video objects ▪ The audio and video elements are represented in JavaScript by the HTML Audio and Video element objects, respectively. Both of these are derived from HTML Media element. ▪ To access a specific audio or video element using JavaScript, we need to set its id attribute. HTML5 multimedia 21 Audio attributes in javascript ▪ Attributes representation in a HTML5 webpage: ▪ ▪ ▪ In javascript, the current state of the audio or video is available through properties such as duration, currentTime, and volume. ▪ Since the audio element will be referenced in numerous places, we can declare a variable to store it. This will avoid the need to search through the DOM every time it is used. HTML5 multimedia 22 Controlling media ▪ The togglePlay() method is called when the user clicks the “Play” button. If the current state of the audio element is “paused” or “ended”, it calls the play() predefined function. Otherwise, it calls the pause() method. ▪ The updatePlayPause() method is registered on the audio element for both the play and pause events. It sets the label of the “Play” button to reflect the state of the audio element. If the audio is currently playing, the text is changed to “Pause” since that will be the result if the button is clicked. Otherwise, the text is set to “Play.” ▪ The endAudio() function is registered with the audio element in response to the “ended” event, which is raised when the audio has finished playing. HTML5 multimedia 23 24 Audio in HTML5 Games HTML5 multimedia Audio in HTML5 games ▪ Sound is a very important (and often neglected) aspect of game creation. Sound is a powerful and efficient tool for establishing mood and feeling, for building tension and excitement, and for controlling the pacing of a piece. ▪ Audio in games is not optional. ▪ Audio is such a very powerful mechanism for conveying action and meaning that even simple sound effects will dramatically improve the feel of your game. HTML5 multimedia 25 Scenario of sound effect ▪ Imagine two identical circles—one on the left side of the screen, one on the right, and both at the same height. The two circles move horizontally, crossing at the center of the screen. When they reach the other side, they move back again until they reach their start positions. ▪ Something interesting happens when we introduce a simple sound. If, at the very moment the two circles intersect, we make a “plop” sound (like a tennis racket hitting a ball), suddenly there’s a strong illusion that the two circles, actually, collide and rebound! HTML5 multimedia 26 Sound control with javascript ▪ The plop example demonstrates the simplest way to get some sound to play via JavaScript. ▪ Create a new Audio element and assign the “source”, in the same way we’d create an Image element. ▪ This is also equivalent to embedding an tag in the main web page, but created on demand when required throughout our game. ▪ When the “tennis balls” collide (their x position offsets are < 5 pixels apart) we call play on the Audio element: HTML5 multimedia 27 Sound control with javascript ▪ Repeating Sounds: By default, all the sounds are one-shot. They play through from start to end, then stop. That’s perfect for most effects (like power-up twinkles and collision explosions). ▪ Other times, we’ll want sounds to loop over and over. To facilitate this, add the loop property as one of our possible options when creating a Sound instance. If looping is set to true, we’ll apply it to the Audio element (via its corresponding loop property). HTML5 multimedia 28 Sound control with javascript ▪ Then we’ll define it in the options object when making the game’s loopable sound element: ▪ If a player is holding down the up button (controls.y() is less than 0), the jetpack is applying its upward force and the relevant woosh sounds should play: HTML5 multimedia 29 30 Practice In this section: Event and background sounds in games HTML5 multimedia Example of game sounds ▪ Game: Push the buttons to move the red square. ▪ Sound effects: ▪ Hearing a "dunk" when the red square hits an obstacle. ▪ Background music. ▪ Source code available in: https://www.w3schools.com /graphics/tryit.asp?filename =trygame_sound_music HTML5 multimedia 31 Project structure Game ▪ Game: main folder. Res Src Index.html ▪ Res: folder containing the used resources: ▪ css file, ▪ audio files (event.mp3 and Sound Main.css Main.js theme.mp3 sounds). ▪ Src: folder containing the game’s main script (main.js). event.mp3 ▪ Index.html: main HTML5 webpage of the game theme.mp3 HTML5 multimedia 32 Adding sound ▪ Use the HTML5 element to add sound and music to the game. ▪ In this examples, we create a new object constructor to handle sound objects. HTML5 multimedia 33 Adding sound ▪ To create a new sound object use the sound constructor, and when the red square hits an obstacle, play the sound. HTML5 multimedia 34 Background Music ▪ To add background music to the game, add a new sound object, and start playing when starting the game. HTML5 multimedia 35 Thank you! Multimedia – FWD 142 HTML5 Graphics Applied College Chapter goals and content Understanding the difference between canvas and SVG Graphics on the Web Drawing with the canvas element The canvas element Drawing Scalable Vector Graphics Scalable Vector Graphics Graphics in HTML5 games Using graphics in HTML5 games HTML5 Graphics 2 Graphics on the Web ▪ In the past, all graphics on the web had to be represented by bitmap images in formats such as GIF or JPEG. ▪ Bitmap images: Bitmaps are images defined by a rectangular grid of pixels. The traditional formats used on the web — JPEG, PNG, and GIF — are all bitmap formats ▪ The img tag has been around since forever and has full support in all browsers. ▪ The main disadvantages of bitmap images are that the images don’t scale well and that the content is static and non-interactive. ▪ Animated image formats exist, but you cannot dynamically change the content of the images. Bitmap images don’t have much in terms of interactivity either. HTML5 Graphics 3 4 The Canvas element HTML5 Graphics Canvas ▪ Issue: How to create dynamic graphics? ▪ Solution: Canvas element. ▪ Canvas is one of the major, early features of the HTML5 specification. ▪ The canvas element provides a two-dimensional drawing surface with a rich JavaScript API for drawing all sorts of shapes, paths, and objects on that surface. ▪ A major difference between canvas and SVG is that the canvas API does what is known as immediate mode rendering in contrast to SVG’s retained mode. ▪ Immediate mode means that any content drawn on the canvas is immediately rasterized and rendered to the surface. ‫يتم تحويله على الفور إلى صورة نقطية‬.‫السطح‬ ‫وعرضه على‬ HTML5 Graphics 5 Examples of canvas effects Composite operations Shadow effects Pixel-based canvas effect HTML5 Graphics 6 Drawing with Canvas ▪ Canvas element can be created with JavaScript like any other DOM element:represents the document as nodes and objects; ▪ Alternatively, we can declare it in the markup using the appropriate HTML tags: ▪ This approach creates a canvas element with the default dimensions 300x150 pixels. ▪ When created, the canvas is fully transparent. ▪ You can provide alternative fallback content by adding it as children of the canvas element: HTML5 Graphics 7 Drawing with Canvas ▪ The canvas element does not provide any graphics functionality by itself. It merely defines a two-dimensional surface and exposes a few properties for setting the dimensions: ▪ To add graphics to the canvas surface, we do so via a context object created using the getContext() method on the canvas element: ▪ The canvas element allows for any number of context types (e.g., 2D, 3D graphics with WebGL) with different interfaces to creating graphics on the canvas surface. HTML5 Graphics 8 Drawing shapes and paths ▪ Many of the canvas drawing functions use the same path API to define paths of points that make up the shape you want to draw. ▪ The most basic path function simply adds a line segment. ▪ A path is always made up of several sub-paths. ▪ The first path function called is ctx.moveTo(), which creates a new sub-path with a single point at the specified coordinates. ▪ The ctx.lineTo() method moves the position, adds a new point, and connects it to the previous position with a line. ▪ First, initiate a new path by calling the ctx.beginPath() method on the context object. Invoking this method also clears any previously added path data. HTML5 Graphics 9 Fills and strokes ▪ Now that the path is defined, we can draw it to the canvas surface. ▪ The canvas path API has two different methods for converting the path to graphics: ctx.fill() and ctx.stroke(). ▪ The method ctx.fill() fills the inside of the path with a color, and ctx.stroke() draws only the edges. ▪ The color used for each of these methods is set using the ctx.fillStyle and ctx.strokeStyle properties of the context object: HTML5 Graphics 10 Fills and strokes - Rectangle ▪ The ctx.rect() method allows creating shapes like rectangles with less typing: ▪ The ctx.fillRect() method takes four parameters that define a rectangle that should be filled using the current ctx.fillStyle: HTML5 Graphics 11 Fills and strokes – Triangle and Circle HTML5 Graphics 12 Adding images ▪ Apart from shapes and paths, we also can add both text and images to a canvas. ▪ We can draw images to the canvas using the ctx.drawImage() method on the context: ▪ This method draws an img element, image, to the canvas. ▪ The dx, dy, dw, and dh arguments define the rectangle where the image should go. ▪ The upper-left corner is at (dx, dy), and the lower-right corner is at (dx + dw, dy + dh). ▪ The dw and dh arguments are optional and, if left out, default to the dimensions of the image. ▪ The ctx.drawImage() method can also take both a source and a destination rectangle: HTML5 Graphics 13 Adding text ▪ In HTML5, we can also add text content to the canvas element. ▪ The canvas element behaves essentially like an image on the page, we can apply much of the same logic to text on canvas as we would to text in images. ▪ NOTE. If it is possible to get the same or a similar result using CSS, perhaps we should reconsider going for a canvas-based approach. ▪ For example, regular HTML and CSS are often better suited for elements such as headings and buttons. HTML5 Graphics 14 Adding text ▪ First, specify the font with which the text will be drawn. That is by setting the ctx.font property on the context. ▪ The value can be any font values as known from CSS: ▪ Possible values for ctx.textAlign are (start, end, left, center, right) ▪ Possible values for ctx.textBaseline are (top, middle, bottom, hanging, alphabetic, ideographic) HTML5 Graphics 15 16 Scalable Vector Graphics HTML5 Graphics What is SVG? Characteristics Advantages stands for Scalable Vector Graphics can be created and edited with any text editor can be searched, indexed, scripted, and used to define vector-based graphics for the compressed Web are scalable and zoomable defines the graphics in XML format can be printed with high quality at any resolution Every element and every attribute in SVG files can be animated do NOT lose any quality if they are zoomed or resized a W3C recommendation an open standard integrates with other W3C standards such as the DOM and XSL SVG files are pure XML HTML5 Graphics 17 SVG graphics ▪ SVG is an alternative to bitmap graphics that is useful for displaying vector- based art. Because this format is based on XML, we can edit the files by hand, although many graphics applications also export directly to SVG format. ▪ Example of an SVG file: ▪ We can also add images, text, and various shapes to an SVG file, but we must declare all content in this XML format. ▪ In addition to graphical elements, we can declare basic animations and event handlers. HTML5 Graphics 18 Adding simple shapes ▪ Most images can be expressed as a collection of geometrical shapes. ▪ A circle is expressed as a center point, cx and cy and a radius, r. ▪ A line is specified as a beginning point,x1 and y1; and an endpoint, x2 and y2. ▪ A rectangle (rect) element is described by the top-left corner location, x and y; a width; and a height. ▪ A polygon is defined by a set of points in the form of x1,y1 x2,y2 x3,y3. The initial SVG image HTML5 Graphics without styling 19 Adding Styles ▪ The default style for these elements is a solid black fill, and because some of these shapes are on top of each other, several are not currently visible. ▪ Notice that a class attribute is assigned to each element. ▪ By applying the following CSS rules, the SVG image will look like this: The SVG image with styling applied HTML5 Graphics 20 21 Graphics in HTML5 Games Example: A chess board with moving chess pieces COLLINS, Mark J. Pro HTML5 with CSS, JavaScript, and Multimedia: Complete Website Development and Best Practices. Apress, 2017. HTML5 Graphics Chess game ▪ Game overview: a chess board, with a series of squares with alternating colors. ▪ We use image files to draw the chess pieces in the appropriate squares. ▪ We apply an animation to move the pieces around the board. HTML5 Graphics 22 Drawing the chess board ▪ Create a new web page called “Chess.html”, which contains a canvas element: ▪ Then create a “Chess.js” script file using the following code. HTML5 Graphics 23 Drawing the chess board ▪ Add a function to draw the chessboard to the “Chess.js” file and then call this function using the following code: The initial chessboard HTML5 Graphics 24 Adding the chess pieces ▪ The chess pieces are drawn using image files. ▪ Create an Image object, set its src property as the location of the image file, and then call the drawing context’s drawImage() method like this: ▪ The first parameter of the drawImage() method specifies the image that will be drawn. This can be an Image object. ▪ The next two parameters specify the x and y locations of the top-left corner of the image. The fourth and fifth parameters are optional and specify the width and height, respectively, that the image will be scaled to fit into. HTML5 Graphics 25 Adding the chess pieces ▪ To draw the chess pieces, create a new folder in the web application, called Images, to store the image files. ▪ Add the following variable declarations to the beginning of “Chess.js” file (just after the chessCanvas and chessContext variables). This will define a variable to reference an Image object for each of the 12 image files. It will also define an array that we will be using to store the 32 chess pieces. HTML5 Graphics 26 Adding the chess pieces ▪ Add the loadImages() function to the “Chess.js” file. HTML5 Graphics 27 Adding the chess pieces ▪ To define the chess pieces, we will use an object definition that will store the properties needed to draw the chess piece. ▪ The image property contains a reference to the appropriate Image object. ▪ The x and y properties specify the square that the piece is in, from 0 to 7, left to right and top to bottom. ▪ The height and width properties indicate the size of the image, which will vary depending on the type of piece. ▪ The killed property is used to indicate whether the piece has been captured. Captured images are not displayed. ▪ Add the following code to the “Chess.js” file: HTML5 Graphics 28 Adding the chess pieces ▪ Add the following functions to the “Chess.js” file. This implements the drawPiece() function that draws a single chess piece based on the class properties. It also implements a drawAllPieces() function that will draw each of the pieces defined in the pieces array. ▪ Now we need to create 32 instances of the ChessPiece class and specify all of the appropriate properties. Add the createPieces() that creates the instances of the ChessPiece class, storing them in the pieces array, and sets the properties of each one. HTML5 Graphics 29 Adding the chess pieces HTML5 Graphics 30 Adding the chess pieces ▪ Modify thedrawBoard() function to also call drawAllPieces() after the board has been drawn. ▪ Finally, replace the call to drawBoard() function in the “Chess.js” file with the following code. This will call the loadImages() and createPieces() functions and wait 1 second before calling drawBoard(). Chess board with the pieces displayed HTML5 Graphics 31 Moving chess pieces ▪ To move a piece, we just need to update the x or y property and then redraw it. ▪ The function that draws each piece computes the location based on the square that the piece is in. ▪ The makeNextMove() function adjusts the x and y positions of a chess piece and then redraw the board and all of the pieces. We will use the setInterval() function to call this repeatedly so the pieces will move in succession. ▪ Add the following variables near the beginning of the “Chess.js” file: HTML5 Graphics 32 Moving chess pieces ▪ Implement the makeNextMove() function in the “Chess.js” file using the following code: HTML5 Graphics 33 Moving chess pieces ▪ The code, in the makeNextMove() function, “moves” a piece by adjusting its x and y properties. It keeps track of the move number and uses this to adjust the appropriate piece. ▪ The seventh move captures a piece and sets its killed property. Since this ends the animation, the seventh move also uses the clearTimer() function so no more timer events will occur. ▪ After each move, the board and all the pieces are redrawn. After the seventh move, this function also uses the fillText() method, which is used to write text to the canvas. HTML5 Graphics 34 Moving chess pieces ▪ Add the following code to the “Chess.js” file ▪ This will call the makeNextMove() function every 2 seconds. ▪ The makeNextMove() function will be called by the window object when the timer expires. The completed chess board HTML5 Graphics 35 Thank you Next chapter: HTML5 animations

Use Quizgecko on...
Browser
Browser