fii practic frontend - beenear - laborator3

89
GROW YOUR TALENT WITH US! Iasi, martie 2014 Speakers: Alexandra Constandache [email protected] Alexandru Pradais [email protected]

Upload: beenear

Post on 21-May-2015

199 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Fii Practic Frontend - BeeNear - laborator3

GROW YOUR TALENT WITH US!

Iasi, martie 2014

Speakers: Alexandra Constandache [email protected]

Alexandru Pradais [email protected]

Page 2: Fii Practic Frontend - BeeNear - laborator3

GROW YOUR TALENT WITH US!

Iasi, martie 2014

FRONTEND DEVELOPMENT – LABORATOR 3

Page 3: Fii Practic Frontend - BeeNear - laborator3

HTML

• defines the structure of the page

CSS

• defines the style, or presentation

So HTML + CSS = something well structured that looks OK • something like having the first frame of a movie

• it's ok at first but...don't you want it to do something?

3

Page 4: Fii Practic Frontend - BeeNear - laborator3

4

Page 5: Fii Practic Frontend - BeeNear - laborator3

JavaScript

JavaScript

• Should have been called JavaEngine

Why?

• It turns a simple static page into something

• Active

• Interactive

• It powers the web

• Gives your pages/apps behavior

5

Page 6: Fii Practic Frontend - BeeNear - laborator3

JavaScript Essentials Variables

What they are?

• Containers to hold bits and pieces of information

When they should be used?

• When you need to store the result of some operation for further processing.

6

Page 7: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Defining a new variable for use in code: var myVar;

Anatomy of a variable declaration:

• var - tells the browser that you want to define a new variable

• variables are declared with the same keyword 'var' no matter what their type is

• myVar - the variable name.

! A variable can be defined implicitly without specifying the var

keyword, and only using assignation.

myVar = 10;

7

Page 8: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Things to note about javascript variables

• The names are case-sensitive • This means that myVar is different from MyVar which is different

from Myvar which is… you get the picture right?

• Avoid reserved keywords when defining variables

• as, break, catch, continue, delete, do, null, etc...

• They can be used without an initial

declaration, but that's a big no-no

8

Page 9: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Assigning values to a variable: var myVar = "my variable value";

The variable adjusts it's type according to the value assigned to it.

• That means you can later do something like myVar = 5, and it won't mind

9

Page 10: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Special kinds of values a variable can take • Null value is programmer-speak for “nothing” or “no value”

• Variable defined, initialized/used but now it has no value

• Undefined is used as “no value assigned yet” • Variable defined but it was not initialized yet

• NaN is used as “not a number” • Variable is not a number

• Most often used for testing

if (myObject == null)

{ // There is no myObject in existence. // Now might be a good time to create one.

}

10

Page 11: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Variable Scope • There are 2 basic places where you can

create variables • inside a function

• outside a function

• Local variables are declared inside a function

• local - because they can be used only inside the declaring function

• Global variables are declared outside functions

• global - because they are valid in any function you define

11

Page 12: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

12

localVariable

• will be available and hold information only within the doSomething function

• when doSomething ends, the variable will cease to exist

globalVariable

• will be available while the page is up

• can hold data from multiple functions

• allows passing information from one function to another

<script>

var globalVariable;

function doSomething() {

var localVariable;

...

}

</script>

Page 13: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

What else are variables good for? • To be used in Operations (esp. the numeric ones)

• To control the flow of processes through

• Branching

• Looping

• To pass information to and from functions

• To be part of bigger objects as properties

13

Page 14: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Operations

Most common ones for numerics: +, -, *, /.

var myNumber = (10 + 5) * 2 / 5;

+ can be used to also join strings together

var firstString = "JavaScript"; var secondString = "is Fun"; var myFullString = firstString + secondString;

-, *, / can't be used with string

• the result will be NaN (not a number).

14

Page 15: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

!Warning • JavaScript does automatic type conversion for the

variables used in an expression

» don't mix them up or the result will be...fuzzy

Example:

var myStringNumber = "22"; var myNumNumber = 2; var myResult = myStringNumber + myNumNumber;

15

Page 16: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Previous result:

• myResult is equal to the string "222" and not to the number 24.

• Why?

• Because a string is detected in the expression and an automatic conversion is performed for myNumNumber from numeric to string.

16

Page 17: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Comparisons Are operations that produce a true or false value.

• These results are crucial for branching and looping.

The logical operators can be applied to variables of any type.

• Types can still be mixed but the result might vary sometimes.

Usage var1 logicalOperator var2

17

Page 18: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Logical operators

18

Page 19: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

A couple of fancy operators: === and !==.

They're similar to the equal, not equal operators but surpass them in one aspect: Type checking

=== and !== check if

• the values supplied are the same

• the values supplied come in the same form

• are the same type

19

Page 20: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Ex:

myNumVar = 22; myNumVar2 = 22; myStringVar = "22"; myNumVar == myNumVar2 => true; myNumVar == myStringVar => true; myNumVar === myStringVar => false;

When performing the normal comparison (==) • automatic conversion is performed

22 results equal to "22".

20

Page 21: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Branching

It's about giving the program freedom of choice • To be able to decide based on current values available what block

of code to execute.

The program becomes dynamic

• new input values => new results

21

Page 22: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

Branching constructs

• if - blue

• if...else - red

• nested if...else- blue + red + green

• switch

22

if (y % 2 == 0) { console.log('Even'); } else { if (y % 3 == 0) { console.log('Divisible by 3'); } else { console.log('Not a multiple'); }

}

Page 23: Fii Practic Frontend - BeeNear - laborator3

JavaScript - VARIABLES

The Switch

Is an alternative to the regular if...else statements.

It's used when you need to pick from a large list of values available

23

Page 24: Fii Practic Frontend - BeeNear - laborator3

24

Page 25: Fii Practic Frontend - BeeNear - laborator3

Looping

What it is? A fancy way of saying:

• We want to repeat a block of code x times.

• The number of times can be • known at the start of the loop

• ...or not.

A loop requires 3 elements

• a starting state

• an ending condition

• a way to progress

25

Page 26: Fii Practic Frontend - BeeNear - laborator3

The For loop

26

Page 27: Fii Practic Frontend - BeeNear - laborator3

The While loop

27

Page 28: Fii Practic Frontend - BeeNear - laborator3

JavaScript Functions

A way to group together • variables

• branching statements

• loops • in order to get a certain result or to cause a certain

behavior.

28

Page 29: Fii Practic Frontend - BeeNear - laborator3

JavaScript Functions

Declaring a function

function myFunctionName ([myParameterList])

{ //do something with variables, branches, loops, etc [return some value] }

29

Page 30: Fii Practic Frontend - BeeNear - laborator3

Contents of [ and ] are optional

• a function can be declared and used without input parameters (myParameterList)

• a function can be without having to return some result to the user (return some value)

Because JavaScript doesn't care about types

• parameter types are not needed

30

Page 31: Fii Practic Frontend - BeeNear - laborator3

Ex:

function multiplyNumbers(numberA, numberB) { return numberA * numberB;

}

var someNumber = 23405;

var result = multiplyNumbers(3202, someNumber);

31

Page 32: Fii Practic Frontend - BeeNear - laborator3

JavaScript is pretty understanding

Regarding the difference between the parameter number from the function definition and the number of parameters used in the call.

• If there are more parameters -> the excess is ignored

• If there are less parameters -> the ones missing = Undefined

function quadratic(a, b, c)

{ return -b + Math.sqrt(b*b - 4*a*c) / (2*a); }

var root = quadratic(1, -3, 2, 2, 3, 8);

var root = quadratic(1, -3);

var root = quadratic(1, -3, 2);

The function declaration can be below the call but functions must be in scope when they are called

console.log(square(5));

/* ... */

function square(n){return n*n}

32

Page 33: Fii Practic Frontend - BeeNear - laborator3

Anonymous functions Functions can also be created by a function expression. Such a function can

be anonymous; it does not have to have a name. var square = function(number) {return number * number};

var x = square(4) //x gets the value 16

var factorial = function fac(n) {return n<2 ? 1 : n*fac(n-1)}; console.log(factorial(3));

Function expressions are convenient when passing a function as an argument to another function. function map(f,a) {

var result = [], // Create a new Array

i;

for (i = 0; i != a.length; i++)

result[i] = f(a[i]);

return result;

}

The call:

map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]);//returns [0, 1, 8, 125, 1000].

33

Page 34: Fii Practic Frontend - BeeNear - laborator3

Objects

Are a way to group together variables and functions

• variables are called properties

• functions are called methods

Declaring an object

• with object literals

• with object-definition functions

34

Page 35: Fii Practic Frontend - BeeNear - laborator3

Using object literals

You define an object like so

• var myEmptyPersonObject = {};

Whatever is written between { and } becomes part of the object.

• var myPersonObject = { firstName="John", lastName="PizzaDough"};

The '.' can be used to reference property, methods of an object

• and also to add new ones

Ex:

myEmptyPersonObject.firstName=myPersonObject.firstName myEmptyPersonObject.lastName=" PizzaDough";

35

Page 36: Fii Practic Frontend - BeeNear - laborator3

JavaScript - TYPES

Data types

• Number • Advanced operations using the special predefined object Math:

– Math.abs(x), Math.ceil(x), Math.cos(x), Math.exp(x), Math.floor(x)

• String • Can be considered as objects

• String methods:

– s.charAt(pos) s.concat(s1, ..) s.match(regexp) s.replace(search, replace) s.split(separator, limit) s.substring(start, end) etc

• Boolean

• Object (Function, Array, Date, etc)

36

Page 37: Fii Practic Frontend - BeeNear - laborator3

Using Object Definition Functions

An object definition function

• is a function, like any other

• is used to define all the bits of information related to an object

• uses the keyword 'this' to reference the current object defined

37

Page 38: Fii Practic Frontend - BeeNear - laborator3

Using Object Definition Functions

38

• The function takes as input initialization values for the object properties and creates them

• When using the function the 'new' keyword is mandatory

– without the 'new' we'd just call the function and assign the return value to the object.

function Person(fname, lname) { this.firstName = fname; this.lastName = lname; } var person1 = new Person("Emilio","Shanks");

var person2= new Person("Petro","Shanks");

Page 39: Fii Practic Frontend - BeeNear - laborator3

Be careful around Javascript

Everything in JavaScript is an Object

All properties and methods of an Object are public

Functions hide anything defined inside them

39

Page 40: Fii Practic Frontend - BeeNear - laborator3

Fitting JavaScript into HTML

There are three main ways to use JavaScript 1. Inline <script> element

2. External linked JavaScript file

3. Inline event handlers

40

Page 41: Fii Practic Frontend - BeeNear - laborator3

INLINE <script> element

41

<!DOCTYPE html> <html> <head> <title>Inline script</title> </head> <body> <script> window.alert("Inline script!"); </script> </body> </html>

can be placed in the body or head section

most basic form of including some code in the page

it's called when the page rendering reaches that point.

Page 42: Fii Practic Frontend - BeeNear - laborator3

External linked JavaScript file

42

<!DOCTYPE html> <html> <head> <title>Linked script</title> </head> <body> <script src="myscript.js"></script> </body> </html>

Advantages

• the bulk of the code is all in one place

• the code is reusable in other pages

• easier to use with events

Page 43: Fii Practic Frontend - BeeNear - laborator3

Inline event handlers

43

<!DOCTYPE html> <html> <head> <title>Inline event handler</title> </head> <body> <button onclick="window.alert('Inline event!');"> Click me </button> </body> </html>

Give the page a way of reacting and giving feedback to the user.

Code to call can be written there or a function from an external file can be called.

Page 44: Fii Practic Frontend - BeeNear - laborator3

HTML DOM

What does DOM mean anyway? • Document Object Model

What is The DOM? • DOM Is a cross-platform and language-independent

convention for representing and interacting with objects in HTML, XHTML and XML documents. Objects in the DOM tree may be addressed and manipulated by using methods on the objects

Come again? • Basically, it represents all the stuff present on your page

and allows you to interact with that content and modify it.

44

Page 45: Fii Practic Frontend - BeeNear - laborator3

HTML DOM

Where does this DOM come from? I didn't put it there

• When a web page is loaded, the browser creates a Document Object Model of the page.

What would a visual representation of it look be?

45

Page 46: Fii Practic Frontend - BeeNear - laborator3

HTML DOM

A clear way that we can think of this DOM?

• JavaScript's Sidekick.

Why so? Because through it JavaScript can:

• change all the HTML elements in the page

• change all the HTML attributes in the page

• change all the CSS styles in the page

• remove existing HTML elements and attributes

• add new HTML elements and attributes

• react to all existing HTML events in the page

• create new HTML events in the page

You can also think of it as Batman's cool utility belt.

46

Page 47: Fii Practic Frontend - BeeNear - laborator3

HTML DOM

How do you work with it?

• From inside the JavaScript code • using the document object and its

• methods • properties

Ex: <html> <body> <p id="intro">Hello World!</p> <script> var txt=document.getElementById("intro").innerHTML; document.write(txt); </script> </body> </html>

47

Page 48: Fii Practic Frontend - BeeNear - laborator3

Common uses of the DOM

Finding HTML elements from the page

48

Page 49: Fii Practic Frontend - BeeNear - laborator3

Common uses of the DOM

Changing HTML elements

49

Page 50: Fii Practic Frontend - BeeNear - laborator3

Common uses of the DOM

Adding and Deleting elements

50

Page 51: Fii Practic Frontend - BeeNear - laborator3

Common uses of the DOM

And the best part...

Adding Event Handlers

Ex: document.getElementById(id).onclick=function(){code}

What does it do?

• it adds an event handler for the onclick event of the element with the provided id.

51

Page 52: Fii Practic Frontend - BeeNear - laborator3

NEW semantic elements of HTML5

52

Page 53: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

<div> is the cornerstone of nearly modern web page

• Usually with <div> elements and a healthy pinch of CSS formatting, you can carve an HTML document into headers, side panels, navigation bars, and more.

This technique is good but not transparent.

53

Page 54: Fii Practic Frontend - BeeNear - laborator3

HTML5

HTML4

HTML5 semantic elements for structuring

54

Page 55: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

Why?

• Easier editing and maintenance

• Accessibility

• Search-engine optimization

• Future elements

The new semantic elements behave exactly like <div> elements:

• They group a block of markup, they don’t do anything on their own, and they give you a styling hook that lets you apply formatting.

55

Page 56: Fii Practic Frontend - BeeNear - laborator3

HTML4 quick reminder

<html></html> • The root of an HTML document

<head></head> • Collection of metadata about the document

• <title></title> – Title of the document shown in the a browser’s title

• <base></base> – The base url for all relative URLs

• <link></link> – Used to link JavaScript and external CSS

• <style></style> – Inline style definition

• <script></script> – Defines either an internal script or a link to an external script. The script language is JavaScript.

<body></body> • Represents the content of an HTML document. • There is only one <body> element in a document.

Heading elements: h1 …. h6 • <h1>Heading level 1</h1> <h2>Heading level 2</h2> <h3>Heading level 3</h3> <h4>Heading

level 4</h4> <h5>Heading level 5</h5> <h6>Heading level 6</h6> • <h1> is the most important and <h6> is the least

56

Page 57: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

<main></main> • represents the main content of the <body> of a document or

application.

• This content should be unique to the document excluding any content that is repeated across a set of documents such as sidebars, navigation links, copyright information, site logos, and search forms (unless, of course, the document's main function is as a search form).

57

Note: There must not be more than one <main> element in a document, and it must not be a descendent of an <article>, <aside>, <footer>, <header>, or <nav> element.

<main> <h1>Apples</h1> <p>The apple is the pomaceous fruit of the apple tree.</p> ... </main>

More information: http://html5doctor.com/the-main-element/

Page 58: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

<section></section> • generic section of a document or application

• a thematic grouping of content, typically with a heading

• Example: • chapters, various tabbed pages or numbered sections of a chapter.

• Sections in a web page: split in introduction, news item & contact information

58

<div> <h1>Level 1</h1> <h1>Level 2</h1> <div> <h1>Level 3</h1> </div> </div> <section>

<h1>Level 1</h1> <h1>Level 2</h1> <section> <h1>Level 3</h1> </section> </section>

Page 59: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

<nav></nav>

• a section with navigation links to other pages or to parts within the page

• Links part of a menu

59

<div id="nav"> <ul> <li><a href="#">home</a></li> <li><a href="#">blog</a></li> <li><a href="#">gallery</a></li> <li><a href="#">about</a></li> </ul> </div>

<nav> <ul> <li><a href="#">home</a></li> <li><a href="#">blog</a></li> <li><a href="#">gallery</a></li> <li><a href="#">about</a></li> </ul> </nav>

Page 60: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

<article></article>

• Self-contained composition in a document, page, application or site

• Example: • Magazine/newspaper post, blog entry, forum post…

60

<div class="entry"> <p class="post-date">October 22, 2009</p> <h2><a href="#" rel="bookmark" title="link to this post">Travel day</a></h2> </div>

<article> <header> <p class="post-date">October 22, 2009</p> <h1><a href="#" rel="bookmark" title="link to this post"> Travel day</a></h1> </header> </article>

Page 61: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

<aside></aside>

• section of a page that consists of content that is tangentially related to the content around the aside element, and that could be considered separate from that content

61

<div> <h1>Archives</h1> <ul> <li><a href="/2007/09/">September 2007</a></li> <li><a href="/2007/08/">August 2007</a></li> <li><a href="/2007/07/">July 2007</a></li> </ul> </div>

<aside> <h1>Archives</h1> <ul> <li><a href="/2007/09/">September 2007</a></li> <li><a href="/2007/08/">August 2007</a></li> <li><a href="/2007/07/">July 2007</a></li> </ul> </aside>

Page 62: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

<hgroup></hgroup>

• represents the heading of a section

• used to group a set of h1–h6 elements when the heading has multiple levels, such as subheadings, alternative titles, or taglines.

62

<h1>My Weblog</h1> <h2>A lot of effort went into making this effortless.</h2>

<hgroup> <h1>My Weblog</h1> <h2>A lot of effort went into making this effortless.</h2> </hgroup>

The hgroup element is obsolete in HTML5. HTML specification:

elements must not be used to markup subheadings, subtitles, alternative titles and taglines unless intended to be the heading for a new section or subsection.

How to mark up subheadings, subtitles, alternative titles and taglines http://html5doctor.com/howto-subheadings/

Page 63: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

<header></header>

• a group of introductory or navigational aids

• Can contain an h1–h6 element or an hgroup element, but this is not required, it can contain ordinary information

63

<div id="header"> <h1>My Weblog</h1> <p class="tagline">A lot of effort went into making this effortless.</p> </div>

<header> <h1>My Weblog</h1> <p class="tagline">A lot of effort went into making this effortless.</p> </header>

Page 64: Fii Practic Frontend - BeeNear - laborator3

HTML5 semantic elements for structuring

<footer></footer> • represents a footer for its nearest ancestor sectioning content or

sectioning root element • Example:

• contains information about its section such as who wrote it • links to related documents, • copyright data

• When the footer element contains entire sections, they represent appendixes, indexes, license agreements, and other such content.

64

<div id="footer"> <p>&#167;</p> <p>&#169; 2001&#8211;9 <a href="#">Mark Pilgrim</a></p> </div>

<footer> <p>&#167;</p> <p>&#169; 2001&#8211;9 <a href="#">Mark Pilgrim</a></p> </footer>

Page 65: Fii Practic Frontend - BeeNear - laborator3

65

Page 66: Fii Practic Frontend - BeeNear - laborator3

HTML5 elements list

The list of HTML5 elements is larger than the one specified…

All valid HTML5 elements are listed by the Mozilla Developer Network in their HTML5 Developer Guide at this link: • https://developer.mozilla.org/en-

US/docs/Web/Guide/HTML/HTML5/HTML5_element_list

In the mentioned list you can find for each element the attributes which can be used

66

Page 67: Fii Practic Frontend - BeeNear - laborator3

HTML5 Glitz

67

Page 68: Fii Practic Frontend - BeeNear - laborator3

and maybe next time…

68

Page 69: Fii Practic Frontend - BeeNear - laborator3

HTML5 Audio & Video

69

The main idea is:

• Make noise / watch cats playing piano without the need of a plugin

» No more Flash

• A lot of video/audio formats supported

• It is as easy as adding an image with the <img> tag – Audio in fact uses the <audio> tag

– Video in fact uses the <video> tag

Page 70: Fii Practic Frontend - BeeNear - laborator3

HTML5 Audio

Audio <p>

Hear us rock out with our new song,

<i>Sesame Street Rubber Duckies</i>:

</p>

<audio src="rubberduckie.mp3" controls></audio>

SRC = file name to be played

CONTROLS = tell the browser to include a basic set of playback controls (with the style specific to each browser as shown below (picture from HTML5: The missing manual)

70

!Note: The <audio> and <video> elements must have both a start and an end tag. You can’t use empty element syntax, like <audio />.

Page 71: Fii Practic Frontend - BeeNear - laborator3

HTML5 Audio

In order to create your own controls we can use the following API methods: • play() — plays the audio

• pause() — pauses the audio

• canPlayType() — interrogates the browser to establish whether the given mime type can be played

• buffered() — attribute that specifies the start and end time of the buffered part of the file

• And the following properties • currentTime = playhead position (seconds)

• duration = media duration (seconds) – read only

• muted = is volume muted? (boolean)

• paused = is media paused? (boolean)

• volume = volume level (double)

71

Page 72: Fii Practic Frontend - BeeNear - laborator3

HTML5 Audio

Other <audio> attributes:

• preload – with the following possible values • auto – let the browser decide what to do

• metadata – the browser is told to download a small chunk of information (“metadata”) before playing – like the total length of the audio

• none – the browser is told to hold the download

• When the value of the preload attribute is in {metadata, none} the media is downloaded once it is started to play

• autoplay - start playback as soon as it can

• loop – specify whether the file should be played repeatedly

72

Page 73: Fii Practic Frontend - BeeNear - laborator3

HTML5 Audio

Have you met the codecs ? • In software, an audio codec is a computer program implementing

an algorithm that compresses and decompresses digital audio data according to a given audio file format or streaming media audio format.

• Famous HTML5 audio codecs: Ogg Vorbis, MP3, WAV • How do we know what works where?

– Using the source tag and type attribute:

<audio>

<source src="elvis.mp3" type='audio/mpeg; codecs="mp3"'>

<source src="elvis.oga" type='audio/ogg; codecs="vorbis"'>

<!-- add your fallback solution here -->

</audio>

– Use the canPlayType method which can return: Probably, maybe or an empty string.

» (why? Because the browser can only guess)

» audio.canPlayType('audio/ogg');

» audio.canPlayType('audio/ogg; codecs="vorbis"');

73

Page 74: Fii Practic Frontend - BeeNear - laborator3

HTML5test.com says…

74

Page 75: Fii Practic Frontend - BeeNear - laborator3

HTML5 Video

Video • <video width="640" height="360“

src="http://www.youtube.com/demo/google_main.mp4"

controls autobuffer poster="whale.png" >

<p> Or you can

<a href="http://www.youtube.com/demo/google_main.mp4">

download the video </a> instead.

</p>

</video>

Attributes are similar to the audio tag with few exceptions:

• autobuffer – similar to the audio preload attribute

• poster – useful to display a frame of the video (as a .jpg, .png ….and so on) in case the video doesn’t load the video.

75

Page 76: Fii Practic Frontend - BeeNear - laborator3

76

Page 77: Fii Practic Frontend - BeeNear - laborator3

Audio – Video examples

• Check this online music player: • http://antimatter15.github.com/player/player.html

77

Page 78: Fii Practic Frontend - BeeNear - laborator3

HTML5 Canvas

78

More cool stuff at http://www.html5canvastutorials.com/

Page 79: Fii Practic Frontend - BeeNear - laborator3

HTML5 canvas

Getting started: • <canvas id="drawingCanvas" width="500" height="300"></canvas>

• Initialized as a blank borderless rectangle

• A little css never hurt nobody canvas {

border: 1px dashed black;

}

• To start working with the canvas, we need the reference to the canvas: var canvas = document.getElementById("drawingCanvas");

• Second, we need to setup the 2D context (well there is no 3D context yet) var b_context = b_canvas.getContext("2d")

function draw()

{

var canvas = document.getElementById("drawingCanvas");

var context = canvas.getContext("2d");//future 3D

}

79

Page 80: Fii Practic Frontend - BeeNear - laborator3

HTML5 Canvas

Drawing in Canvas Context:

The esential functions are: beginPath()

closePath()

stroke()

fill()

Properties: fillStyle = (CSS color,pattern,gradient)

strokeStyle= (CSS color,pattern,gradient)

o Drawing lines o moveTo(x, y)

o lineTo(x, y)

80

context.moveTo(10,10); context.lineTo(400,40); context.stroke(); //draws a line from 10-10 to 400-400

Page 81: Fii Practic Frontend - BeeNear - laborator3

HTML5 Canvas

Modifying lines (must be set before stroke)

• Linewidth = width of the line in pixels • context.lineWidth = 10;

• Strokestyle = color of the line in HTML color name and color code • // Set the color (brick red) using an HTML color code:

context.strokeStyle = "#cd2828";

• // Set the color (brick red) using the rgb() function:

context.strokeStyle = "rgb(205,40,40)";

• linecap = decide the cap of the line • butt – squared-off edge

• round

• square - (which looks the same as butt, but extends the line

an amount equal to half its thickness on each end).

81

Page 82: Fii Practic Frontend - BeeNear - laborator3

HTML5 Canvas Drawing lines

// Set the line width and color (for all the lines).

context.lineWidth = 20; context.strokeStyle = "rgb(205,40,40)"; // Draw the first line, with the standard butt

ending. context.moveTo(10, 50); context.lineTo(400, 50); context.lineCap = "butt"; context.stroke(); // Draw the second line, with a round cap. context.beginPath(); context.moveTo(10, 120); context.lineTo(400, 120); context.lineCap = "round"; context.stroke(); // Draw the third line, with a square cap. context.beginPath(); context.moveTo(10, 190); context.lineTo(400, 190); context.lineCap = "square"; context.stroke();

82

Page 83: Fii Practic Frontend - BeeNear - laborator3

HTML5 Canvas

Drawing and filling triangles or any other polygons context.moveTo(250,50);

context.lineTo(50,250);

context.lineTo(450,250);

context.lineTo(250,50);

context.lineWidth = 10;

context.strokeStyle = "red";

context.stroke();

• Filling the triangle means that we need to close the line path with closePath(), pick a color using fillStyle and call fill()

context.closePath();

context.fillStyle = "blue";

context.fill();

closePath also connects the begin point with the last drawn point

Calling fill after stroke means that the stroke will be overlapped with the fill color, if we do not want that, this means stroke must be called after fill

o Drawing rectangles • fillRect(x, y, width, height)

• strokeRect(x, y, width, height)

• clearRect(x, y, width, height)

83

Page 84: Fii Practic Frontend - BeeNear - laborator3

HTML5 Canvas

Drawing text

Context: Context.font= {font}

Context.textAlign={start,end,left,right,center};

Context.textBaseline=

{top,hanging,middle,alphabetic,ideographic,bottom};

o Drawing o Context.fillText(text,x,y);

84

Page 85: Fii Practic Frontend - BeeNear - laborator3

HTML5 Canvas

This is just a taste of it…. Canvas can do a lot of things: • Draw different arcs

• Draw with gradients

• Draw with transparency

• Draw full images

• Transform the context

• Make composite operations by indicating how overlapping figures must look

• Interact with the user

You can read more about them on: • http://www.html5canvastutorials.com/

• https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial

85

Page 86: Fii Practic Frontend - BeeNear - laborator3

Canvas demos

• http://htmlfive.appspot.com/static/gifter.html

• http://html5demos.com/canvas-grad

86

Page 87: Fii Practic Frontend - BeeNear - laborator3

Bibliography

HTML5: The Missing Manual by Matthew MacDonald

JavaScript by Mozilla Developer Network

• https://developer.mozilla.org/en-US/docs/Web/JavaScript

DIVE INTO HTML5 by Mark Pilgrim http://diveinto.html5doctor.com/

HTML5 Doctor: http://html5doctor.com/ Other HTML5 demos …well check this out: http://html5demos.com/

For beginners: • http://www.w3.org/community/webed/wiki/HTML/Training

• http://www.w3.org/community/webed/wiki/HTML/Elements

87

Page 88: Fii Practic Frontend - BeeNear - laborator3

Now a little test

88

Page 89: Fii Practic Frontend - BeeNear - laborator3

Thank you!

89