Scripting & Interactivity

Download Report

Transcript Scripting & Interactivity

Scripting &
Interactivity
Digital Multimedia, 2nd edition
Nigel Chapman & Jenny Chapman
Chapter 16
This presentation © 2004, MacAvon Media Productions
16
536
Event-Driven Systems
•
•
Associate actions with events, so when the
user does something, something happens in
response (interactivity)
Most events initiated by user actions
•
•
Mouse clicks, mouse movements, key
presses, &c
Actions defined by little programs (scripts) in a
scripting language
© 2004, MacAvon Media Productions
16
537–538
Scripting Languages
•
•
'…a programming language that is used to
manipulate, customize, and automate the
facilities of an existing system.' [ECMAScript
Specification]
Provide control structures and basic types for
computation, plus objects and data types
belonging to some host system
•
e.g. JavaScript: core language plus objects
representing browser window, document,
etc
© 2004, MacAvon Media Productions
16
538–539
ECMAScript
•
•
•
•
Standard based on JavaScript and JScript
(Netscape and Microsoft scripting languages for
WWW)
Produced by European Computer Manufacturers'
Association (ECMA)
Only defines a core language, which is not
computationally self-sufficient
Must be augmented with host objects to manipulate
a host system
e.g. JavaScript = ECMAScript + host objects for
a Web browser (W3C DOM)
•
© 2004, MacAvon Media Productions
16
540–543
Values and Expressions
•
•
Three types: number, string and Boolean
Numbers and arithmetic follow usual rules,
using C-like operators (+, -, *, /, %)
Internally all arithmetic is double-precision
floating point
•
•
•
String literals in " " or ' ', usual \ escapes, +
used as concatenation operator
Boolean values are true or false; combine with
Boolean operators (!, &&, ||)
Results of comparisons are Boolean
•
© 2004, MacAvon Media Productions
16
543–544
Variables
•
•
Named locations that can hold a value
ECMAScript variables are untyped
•
•
The same variable can hold a number, string or
Boolean at different times
No need to declare variables before use, but you can
•
var book = "Digital Multimedia", edition = 2;
© 2004, MacAvon Media Productions
16
544–545
Assignment
•
= is the assignment operator
•
•
•
Simple assignment: variable = expression;
Left hand side can be more complicated
Compound assignment operators +=, *= etc
provide shorthand for common pattern:
•
•
x += a is equivalent to x = x+ a etc
x++ and ++x are equivalent to x += 1
•
Pre- and post-increment
© 2004, MacAvon Media Productions
16
545–546
Control Structures
•
•
Sequence, iteration (loops), selection
(conditionals – if…)
S1 ; S2; …
•
•
; is a statement terminator
if (E) S1 else S2
•
•
else S2 may be omitted
S1 and S2 may be blocks – sequences
within { … }
© 2004, MacAvon Media Productions
16
547
Conditionals
•var
commission = amount * 0.1; // 10% = 0.1
if (commission < 10)
payment = 0;
else
payment = commission;
• Note use of comment
• Alternative version
•payment = amount * 0.1;
if (payment < 10) payment = 0;
© 2004, MacAvon Media Productions
16
546–549
Loops
•
•
while (E) S
for (initialization; condition; increment) S
•
•
For-loop is a neater and more compact
equivalent for the common pattern:
initialization;
while (condition)
{ S ; increment; }
© 2004, MacAvon Media Productions
16
548–549
Loop Examples
•var
ss = "", i = 0;
while (i < repetitions) {
ss += s;
++i;
}
•or, equivalently:
•for (var ss = "",
i = 0; i < repetitions; ++i)
ss += s;
© 2004, MacAvon Media Productions
16
549
Arrays
•
Aggregate data structures
•
•
•
Collection of values that can be treated as a
single entity and may be assigned to a variable
An array is an aggregate data structure consisting
of a sequence of values
Each element of the array can be identified by a
numerical index – its position in the sequence
© 2004, MacAvon Media Productions
16
549
Indexing Arrays
•
Array a, a[0], a[1], a[2],… are its first, second,
third,… elements
•
•
N.B. Index values start at 0, not 1
If E is any expression with a numerical value of
0 or more, a[E] gives the value of the array
element at the corresponding position
•
e.g. if x = 9, a[2*x + 1] is the same as
a[19], but the value of x can be computed
dynamically
© 2004, MacAvon Media Productions
16
550
Array Operations
•
Create an array:
•
•
•
a = new Array();
No need to specify the number of elements,
the array will grow as needed
Number of elements in a is a.length
•
•
Highest element is a[a.length-1]
a[a.length] is the first free element
© 2004, MacAvon Media Productions
16
551
Iterating Over Arrays
•
•
Use loops of the form:
for (var i = 0; i < a.length; ++i)
For example:
var total_users = 0;
for (var i = 0; i < browser_users.length; ++i)
total_users += browser_users[i];
var mean_users =
total_users/browser_users.length
© 2004, MacAvon Media Productions
16
551–552
Associative Arrays
•
Array indexes may be strings
•
Implement lookup tables – mapping from
strings to values
•
•
•
month_values["Jan"] = 0;
month_values["Feb"] = 1;
month_values["Mar"] = 2;
Use same indexing notation as numerically
indexed arrays:
month_values[month_name]
© 2004, MacAvon Media Productions
16
553
Functions
•
•
Form of abstraction
Give a name to a
computation (define a
function), perform the
computation by using
the name (call the
function)
•
•
Black box
Arguments ⇒ Result
© 2004, MacAvon Media Productions
16
553–554
Function Definition
•
•
•
•
function (formal parameters) { body }
Formal parameters behave like variables within
function body
Values of arguments are assigned to the formal
parameters when the function is called
Body may include a return statement; the
value of the following expression is the result
© 2004, MacAvon Media Productions
16
553–554
Function Example
•function
rake_off(amount)
{
var payment;
var commission = amount * 0.1;
if (commission < 10)
payment = 0;
else
payment = commission;
return payment;
}
•var
year_total = 12*rake_off(11450);
© 2004, MacAvon Media Productions
16
554–555
Objects
•
•
ECMAScript is object-based
An object comprises
•
•
•
A collection of named data items, known as
properties
A collection of operations (functions), known
as methods
Use dot notation to access properties and
methods: the_win.x_pos, the_win.close(), etc
© 2004, MacAvon Media Productions
16
556–557
Built-in Objects
•
•
•
Math
Properties are useful constants, such as
Math.PI, Math.SQRT2, Math.E
Methods provide trig functions, exponentials
and logs, random numbers,…
•
•
Array
All arrays inherit properties and methods,
e.g. Array.length
•
String
Useful methods for operating on strings,
inherited by all strings
•
© 2004, MacAvon Media Productions
16
558
WWW Client Scripting
•
•
Scripts can modify browser's display in
response to user events (e.g. rollovers),
validate form input
W3C Document Object Model (DOM) defines a
language-independent, abstract interface to
Web browser
© 2004, MacAvon Media Productions
16
558–559
The document Object
•
•
•
document provides an interface to the HTML
document currently being displayed
Properties hold title and elements of the HTTP
request (URL, referrer, etc)
write method writes its argument into the
current document
•
•
Dynamically generated content
getElementById returns an object
corresponding to an element with an id
© 2004, MacAvon Media Productions
16
559–561
Scripts in Web Pages
• Use the script element to embed a script
•<body>
<script type="text/javascript">
document.write('<h1>' + document.title + '</h1>');
</script>
</body>
• Script is executed at the point it is encountered, its output
replaces the script element
•
Scripts may be placed in the document's head
© 2004, MacAvon Media Productions
16
562
Event Handlers
•
Elements may have special attributes, whose
name identifies a class of events, value is a
piece of code to execute when the event occurs
•
•
onClick, onMouseOver, onKeyPress, …
Often the value is a call to a function (event
handler)
•
Usually defined in a script in the
document head
© 2004, MacAvon Media Productions
16
562–563
Rollovers
•
•
•
Implemented by changing the src attribute of
an img element
The document.images array contains objects
for all images in the document
Use onMouseOver and onMouseOut handlers to
change the image as the cursor moves over
and leaves the image
© 2004, MacAvon Media Productions
16
563
Rollover Example
• Handlers defined in document head:
•function in_image() {
document.images['circlesquare'].src =
'images/circle.gif';
}
function out_of_image() {
document.images['circlesquare'].src =
'images/square.gif';
}
Trigger element
< img src="images/square.gif" alt="square or circle"
onMouseOver="in_image()" onMouseOut="out_of_image()"
id="circlesquare" />
•
•
© 2004, MacAvon Media Productions
16
566–567
Scripts and Stylesheets
• Each element's object has a style property, which
has properties corresponding to the styles applied to
the element
• By assigning to properties of the style, the element's
appearance, position etc can be changed
•document.getElementById('intro').style.color
= 'black'
© 2004, MacAvon Media Productions
16
570–573
Behaviours
•
•
•
For common tasks, remove the necessity for
scripting by providing parameterized actions,
known as behaviours
Behaviour is an abstraction of a class of actions
(e.g. display a message); specific action is
generated by providing values for the
behaviour's parameters (e.g. text of a
message)
Authoring systems (Dreamweaver etc) provide
an interface for applying behaviours and
setting parameter values
© 2004, MacAvon Media Productions
16
573–574
Scripting in Flash
•
•
•
Flash's ActionScript language is ECMAScript with
a set of host objects corresponding to elements
of Flash movies
Also has objects for analyzing XML data,
communicating with servers, … for building Web
applications with Flash front-ends
Use Flash's Actions panel to create scripts
•
Just type code, or build scripts by adding
constructs from a list and supplying
parameters
© 2004, MacAvon Media Productions
16
575–576
Frame Scripts
•
Attached to any keyframe
•
•
•
•
Create a layer for scripts with keyframes
where needed
Define functions in a dummy frame at start
of movie
Executed when the playhead enters the frame
Modify order of playback with goToAndPlay etc
functions
© 2004, MacAvon Media Productions
16
575–576
Loop 6 Times
• Initialization at start of movie
•var loop_count=0;
• Label start of loop loop
• Script attached to last frame of loop
•if (++loop_count < 6)
gotoAndPlay("loop");
© 2004, MacAvon Media Productions
16
576–577
Button Symbols
•
Type of symbol that responds to user input
•
•
Somewhat redundant now, but originally the
only way to do so, and often convenient
Animations with exactly four frames
•
•
Up, Over, Down and Hit
First three correspond to states of the
button, Hit defines the area in which it
responds to mouse events
© 2004, MacAvon Media Productions
16
577–578
Button Actions
•
•
•
Create instances of button symbols by
dragging on to the stage
Attach event handlers to button instances
Events: press, release, releaseOutside,
rollOver, rollOut, dragOver, dragOut, keyPress
•
•
Visual rollover effect happens automatically
if Up and Down frames are different
Conventional button control just needs
on(release) { … } handler
© 2004, MacAvon Media Productions
16
579
Movie Clip Actions
•
•
•
Any movie clip can receive events and have
scripts attached to it
Slightly different, more general set of events
than for buttons
As well as user input, movie clips can also
respond to events related to loading and
unloading and the receipt of data
© 2004, MacAvon Media Productions
16
579–583
Movie Clip Objects
•
Scripts can control the behaviour of movie clips
•
•
•
Possibility of interactive animation
If you want to control a clip, you must give it
an instance name
Can then call methods and access properties
using the instance name and dot notation
•
•
theClip.stop()
theClip._alpha
© 2004, MacAvon Media Productions