Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Foundation HTML5 Animation with JavaScript, Notas de estudo de Informática

Animação com JS e HTML5

Tipologia: Notas de estudo

2014

Compartilhado em 30/08/2014

david-ubiratan-4
david-ubiratan-4 🇧🇷

4.9

(13)

16 documentos

1 / 488

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe Foundation HTML5 Animation with JavaScript e outras Notas de estudo em PDF para Informática, somente na Docsity!

For your convenience Apress has placed some of the front

matter material after the index. Please use the Bookmarks

and Contents at a Glance links to access them.

xix

Introduction

This book is about how to create interactive animations for the web using computer code and math. But don't worry if you can't remember anything from your high school algebra class, you'll just need a minimal understanding to get started. The purpose of this book is to give you the tools to create and express your ideas, it's not about memorizing equations or theory—although I do explain the underlying ideas—but the practical application of techniques to incorporate in your work. These are concepts and formulas that you will see working, in real-time, right in front of you. Think of this book as the elements of motion, a catalog of ideas to mix, match, and reference.

There are plenty of examples to play with, and it's very satisfying to watch something you've created move around on screen—as if almost alive. But it can be even more satisfying to share this experience with your friends by simply giving them a link to follow in their web browsers—this is the great benefit to distribution using the Internet.

This book is a rewrite of the brilliant work by Keith Peters, Foundation ActionScript Animation. However, instead of targeting Flash, this book uses modern web technologies like the HTML5 and JavaScript. The malleability of this book is a result of the portability of its underlying concepts—the math is the same. When you understand these basic building blocks, you are no longer reliant on the tools provided by someone else, but you can implement these ideas wherever your programming life takes you.

Since the examples in this book are implemented using HTML5 and JavaScript, I'll step you through the particular programming techniques you'll need to understand them. JavaScript is a fun, powerful, and relatively small language, but it can be quirky and idiosyncratic largely because of its flexibility. While other, more structured, languages impose a particular way to program, JavaScript allows you to write code in many different styles. This freedom is powerful, but it can be confusing for a beginner to work out the main ideas of the language. If this is your first time using JavaScript, it would be wise to skim through a proper introduction before working through the examples in this book. The biggest confusion when learning JavaScript is the assumptions you bring from other languages. Keep the reference documentation handy and, if in doubt, test your code snippets in your browsers development console. If you are Flash developer, resist the temptation to think of JavaScript as a variation of ActionScript. It has it's own unique program structure and style, and you will avoid problems later on by leaving behind any preconceived ideas about the language now.

This was a fun book to write, and I hope you have fun working through it. Write your programs, experiment with them, share, and learn from others. Creativity is an active process, and not something you sit around and wait for, so let's get coding!

Part I

JavaScript Animation Basics

CHAPTER 1

techniques and mathematical concepts are language-agnostic. We target the web browser here, but given modest graphics support wherever your coding environment, these formulas and examples are applicable anywhere. Sure, you can skip this chapter if you can’t wait to write some code. But it's strongly suggested you come back to it at some point. If nothing else, you’ll find some insights into how animation works.

What is animation?

Animation is motion. Motion is a change in the position of an object over time—one minute it is here, the next minute it is over there—and space between those two points. By applying mathematical formulas to an object’s location, you can determine its next position and affect the behavior of the movement—breathe life into it. But animation is not just movement, it's change in any visual attribute: shape, size, orientation, color, etc. A ball squishes, plants grow, faces contort—something changes. Some of the earliest computer animations cycled colors to simulate movement; for instance, you can make a waterfall composed of pixels in various shades of blue that appears to alternate hues with such frequency to look like falling water, though nothing on the screen has actually changed position. Time is a fundamental component of animation. It is the mechanism used to express change in an object from one position to the next. And without time, there is no motion—it is a still image and not an animation. Consequently, without motion, we have no sense of time, even if it is present. Take for example, a video of an empty parking garage from a security camera. Without movement, it is impossible to decide if you are watching a live stream, a frame from 5 seconds ago, or an unchanging still image. Only when a plastic bag blows across the screen are you assured that time is present and further change can occur. Without time, nothing else happens in the picture. This brings up another point, animation keeps us interested. If something changes, our brains naturally become curious. What changed? Why did it change? Did I cause it to change? Does this change fit within the mental model I’ve constructed for this object or do I need to adjust my assumptions? Temporal media types such as music and film are compelling because, as in life, we are not sure what will happen next. We may have a general idea, and discerning these patterns is pleasurable, but we find joy in tickling the boundaries of the unexpected. Nontemporal media—images, paintings, text—do not change; we may explore the details of the work and our understanding and interpretation might change over time, but the work will not. This is what makes animation so gripping. Change is inherent to the medium; it captures a part of our experience that we are naturally attuned to. Thus, we are able to get lost in a movie for hours or enthralled by a video game for days. If something is going to happen, generally we want to know what that is.

Frames and motion

Animation is a process that creates the illusion of motion. Nearly every form of projected motion media uses frames to accomplish this.

BASIC ANIMATION CONCEPTS

Frames are a series of discrete images shown in rapid succession to simulate motion or change in an object. Frames are the basis for anything you see on a computer, television, or movie screen. This idea goes back to the earliest cartoons. Animators drew individual pictures on sheets of cellophane (known as cells) , and the earliest motion pictures used a similar technique with multiple photographs.

The concept is simple: You show a bunch of images that vary slightly from one to the next, and the mind blurs them together as a single, moving image. But why do we insist on calling it an illusion of motion? If you see a man walk across the room on a movie screen, is that not motion? Of course it’s only an image of a man, not a real person, but that’s not the reason we don’t consider it motion.

Remember, moving objects travel from a point here to a point there by passing through the intervening space. That is real motion; objects move through space smoothly, not in several jumps. But frame-based motion does just that. It doesn’t move from spot to spot, it disappears and reappears in another location in the next frame. The faster it’s moving, the bigger jump it takes.

If you were shown a picture of a man on the left side of a room and then a few seconds later another picture of the same man on the right side of the room, you’d infer that there are two pictures, not an animation. If you were shown a half dozen pictures of the man in the process of crossing the room, you’d still interpret these as a series of individual photographs. (See Figure 1-1 for an example of this.) If the images were presented fast enough, it wouldn’t change the fact they remain a bunch of still photos, but, you would no longer see it that way. Your mind will process it all as a man moving across the room. It is no more real motion than the original two photos were, but at some point, the mind gives up and buys into the illusion.

Figure 1-1. A series of still photographs by Eadweard Muybridge

This point has been extensively examined by the film industry. Researchers have found that at a rate of 24 frames per second, people will accept these frames as a single moving image. Go much slower than that, and the jumpiness gets annoying and starts to break the illusion. And it seems that the human eye can’t distinguish frame rates higher than that—showing 100 frames per second won't make your animation seem any more realistic (although higher frame rates in a programmed animation can result in more responsive interaction and will seem smoother).

BASIC ANIMATION CONCEPTS

But a coded animation isn’t necessarily interactive. You can take an object and, using code, move it from a particular position across the screen. Each time the animation is played, the same code runs, causing the same movement. This is an example of what we'll call a static animation. Each frame, from start to finish, is predefined. Similar to a movie, you’re watching a predetermined sequence of images that do not change on another viewing. But what if you create an object, and again, using code, determine a random point to place it and a random direction and speed to move it? Now, each time you play the animation, something different happens. Or, what happens if, when the animation starts, you determine the time of day and month of the year, and use that data to create a scene—a winter morning, a summer afternoon, visually distinct images depending on the date the program is run? Or, maybe you have some factors in your animation that change using input from the keyboard and mouse while it runs. This enables the user to interact with the objects on the screen, and about as far from static as you can get. Perhaps the most interesting aspect of dynamic animation, and the focus of this book, is the application of real-world mathematics and physics principles to objects in the animation. You're not limited to moving an object in some random direction; you can also give it some gravity, so that as it moves, it falls down. When it hits the “ground,” it bounces, but not as high as it started out. Then it eventually settles down and just sits there. You can also add some user interaction, enabling the user to “pick up” the object with the mouse or move it around with the keyboard. As the user throws the object around, she gets the feeling of handling a physical object. With this kind of animation, the user is no longer a passive recipient of a sequence of frames that plays out, but has entered an environment you created. You can construct a world that models the physical constraints of your own, providing a more realistic experience, or, you can completely disregard such worldly confines. As the programmer, you are free to express your vision as you see fit. These are the joys of creative coding; by offloading tasks to the computer and having a constantly updating visual display, you can create rich scenes that involve the viewer in a way no medium in human history has been able to do before. How long will viewers stay there? They will remain as long as the environment keeps them interested. The more they interact with it, the more likely they'll come back for more.

Summary

In this opening chapter, the basics of animation theory have been summarized. We build on the concepts of frames and dynamism to create motion and interactivity in our animations. In the following chapters, we examine the mathematical elements of movement and build a collection of tools that you'll incorporate into your programmed animations to create motion, and include lessons on how to use them. What you create with these tools is entirely your decision. The most obvious applications of the techniques in this book are for game creation. Games are essentially interactive animations with some goals for players to achieve. But this is not simply a game-programming book. These techniques are applicable to a wide range of animated projects—from navigational systems, to advertisements, to educational applications, and to interactive art.

CHAPTER 1

A new era of web programming creativity has begun thanks to the innovation driving modern browsers. With the HTML5 canvas element, you have a standards-compliant, cross-platform component for creating advanced web graphics. This book is an exploration into the principles of programmatically generated movement for creating these next-generation graphic interactions.

CHAPTER 2

This book focuses on the rules for dynamic animation, providing different techniques to change the image description, which results in realistic motion. In this chapter, you see how to structure the initial description, how to apply those rules on each frame, and how to tie the program together. You will create plenty of working examples as you progress.

An introduction to HTML

In this book, we create HTML5 documents that are viewed in a web browser. HTML5 is the latest iteration of HTML, Hypertext Markup Language, a language for structuring and presenting content for the World Wide Web. HTML elements are the building blocks of web pages. At the time of writing, the HTML specification is still in development, but a number of features are considered stable and ready to use, such as the canvas element. HTML5 improves on HTML4, which was standardized in 1997, by adding new elements and support for multimedia content, such as audio and video. Because these new, semantically meaningful elements expose properties and controls that are accessible in the document, you can manipulate them programmatically using JavaScript, giving you a powerful way to control and create media. HTML5 is a collection of individual features. When assessing a particular browser’s HTML5 support, this is not an all-or-nothing classification; rather, you test if a browser supports a specific feature of the defined specification. Different browsers have different support for different features. This can make it difficult to target individual HTML5 elements without knowing how a user will view the document. As browsers continue to improve, cross-platform feature detection becomes less of a concern, but for now, you should always test the user's web browser for the HTML5 features you target and provide a backup solution if it fails—even if it’s just a politely worded message instructing your user to upgrade his browser.

Canvas support

The good news, at least for this book, is that all the major browser vendors have implemented support for the canvas element. This means that you can be relatively confident that your user can see the animation you create, provided she has upgraded to a recent version of her browser. Games and animations provide an excellent way to push users into upgrading their browsers, because, after decades of video games, most people understand that cutting-edge graphics require the latest hardware and software. At least it’s easier to convince someone to upgrade her browser rather than buy a brand new gaming console. In case the canvas element is not supported in a web browser, in your HTML document, you can provide backup content by including it within the canvas tags:

**

This browser does not support thecanvas element.

** The warning message appears only if the browser does not recognize the canvas tag. If the browser does

support it, then it renders the canvas element and ignores the nested

element.

To programmatically test whether the browser supports the canvas element, you can add the following JavaScript to your document:

### BASICS OF JAVASCRIPT FOR ANIMATION

if (document.createElement('canvas').getContext) { console.log("Success! The canvas element is supported."); }

This code creates a new canvas element and tests for the existence of its getContext property, which the

object has if it's a valid HTML5 canvas element. If the browser does have support, it prints a message to the debugging console letting you know. Table 2-1 lists the most popular web browsers and the minimum version required for basic support of the canvas element.

Table 2-1. Canvas Element Support for the Major Browsers

IE Firefox Safari Chrome Opera iOS Safari Android Browser 9 3.5 3.2 9 10.6 3.2 2.

Performance

Programming graphics has always been—and for the foreseeable future, will be—a very computationally demanding operation. The reason is simple: The more you can do, the more you want to do and the more demands you place on the performance of the system. The past 25 years of video game history has been an amazing journey of technical advances, evolving from the blocky characters featured in dedicated arcade machines, to fully immersive 3D worlds run on today’s consoles. But still, we want more. Sometimes we judge computer animation against features of the natural world: character realism, lighting effects, and physics. It’s quite a marvel that these simulations can hold up to the scrutiny of human perception, and yet, they often do. We’re still at the dawn of computer animation, and as long as computers keep getting faster—with the help of Moore’s Law—and developers keep refining their techniques, our abilities for visual creation in the future seem almost unlimited. But animation on the web using the canvas element is at the incubation stage, only now considered a viable alternative to using plug-ins like Adobe Flash. In recent years, developers have pushed the boundaries of speed and performance in web browsers and JavaScript engines, and because this is still a highly competitive area, we can look forward to more optimizations and improvements to come. The examples in this book are written so they run at a smooth, reasonable performance on a relatively modern computer and web browser. The capability of your computer will differ from mine, so as you examine the source code in this book, feel free to adjust the values so the examples run smoothly on your machine. Plus, there is no better way to learn how the formulas work than by experimenting with their parameters and observing the output. However, before you share any animations with the world, test them on as many different devices as you can. As more people use mobile phones and tablets—instead of more traditional desktop computers—to access the web, developers need to account for a wide range of device performance differences. Testing and measuring on all these platforms is the only way to ensure your code remains performant.

BASICS OF JAVASCRIPT FOR ANIMATION

use a default setting (wrongly), causing the page to display incorrectly. It's best to explicitly set the character encoding here and avoid the potential confusion.

All valid HTML5 documents contain a title element, which is also placed in the header. Because we use

a CSS stylesheet, create a link element that points to an external file. This contains the style definitions

for our document; we’ll look at the style.css file in a moment.

With the header set, let’s look at the rest of the document:

**

**

In the body element, we place a canvas element. This is what we draw to and reference from our scripts.

Give the canvas an id name and a height and width value so you can see it, and use its id to access

the element with the DOM interface.

After the canvas element, add a script tag that includes the JavaScript code for each example. We’ve

placed the script after the other elements, right before the closing body tag, so that the browser loads

the rest of the document before executing the script. Also, if the script is loaded from a file—possibly from a different server—it won’t hold up the rest of the document while waiting to download. This makes loading faster and the document more responsive.

The skeleton script is simple and effectively does nothing. The window object is the top of the Document

Object Model and how we access the DOM. When the document has finished loading, the window object

executes the function assigned to its onload property:


The example code in this book is placed within the window.onload callback function. Because this

method is executed after all the document elements have been loaded, we can be assured that the canvas element is ready to go by the time the code is called. Consequently, if your document contains a lot of data

embedded in it, such as large images, you can wait a long time for window.onload to execute. In this

situation, it might be better to load the assets using JavaScript, which I show you how to do in Chapter 4.

Finally, we close out our script , body , and html tags. We’re finished creating a basic but perfectly valid

HTML5 document.

CHAPTER 2

CSS stylesheet

In the document header, we created a link to a CSS stylesheet. Now, let’s look at that file. The style

definitions for this book are intentionally minimal; only the background color of the document body and

canvas element has been declared. By default, the canvas background color is transparent, which might

be the color you want, but has been changed to white so you can see exactly where the element is

positioned in the document. Here’s the stylesheet for the style.css file:

body { background-color: #bbb; }

#canvas { background-color: #fff; }

This assumes the document contains an element with an id of 'canvas'. As a document gets more

complicated, so does its stylesheet. The HTML file defines the structure of the document, whereas the CSS stylesheet defines the style or look of the elements. In general, it’s best to organize your content, style, and scripts in separate files.

Additional scripts

As the examples get more complicated and you need to reuse portions of code, it becomes convenient, if not necessary, to move these pieces into separate files for clarity. This is done when declaring new classes that are used across multiple exercises and for functions whose verbosity would distract from the point at hand.

Throughout this book, we'll maintain a file of these utility functions; it’s named utils.js. This script

contains functions that set up boilerplate code for the examples, so that you can concentrate on the underlying animation principles. Each function is explained as they are introduced, so you don’t have to think of this file as a black box. In this file, many of the utility functions will be added as properties to a global JavaScript object named

utils. This way, you can avoid cluttering up the global namespace with a bunch of functions. Be sure that

at the top of the utils.js file you’ve declared an empty object like the following:

var utils = {};

To import this file and other scripts into your document, create a script element and set its src attribute

to the location of the file. Include these immediately before the example code to be certain that everything has loaded properly before attempting to use it:


CHAPTER 2

After you have opened a web developer console, you can type JavaScript expressions directly into the browser and have them evaluated. Try it by entering these statements:

console.log("Hello, World!"); 2 + 2 From the console, you can access DOM elements and script variables to inspect their values (provided they are in the proper scope), which makes it easy to reason about how your program runs. This is a great way to test and debug small sections of code before committing them to a larger program. Find those bugs as early as possible!

Animating with code

With the document structure in place, you should now understand enough of the basics to start coding. You need a text editor to input the examples and an HTML5-capable web browser to run them. For debugging, you should be familiar with your browser’s built-in developer console. After you have these tools—which may already be on your computer—you’re ready to go. Let’s dive in to some animation!

Animation loops

Almost all programmed animation is expressed as some kind of loop. If you think about a frame-by-frame animation, you might create a flowchart resembling a series of images, where each frame just needs to be drawn, as shown in Figure 2-2.

Figure 2-2. Frame-by-frame animation When you start drawing shapes, though, things are a bit different. JavaScript code won’t create and store a new image for each frame, even in a frame-by-frame animation. For each frame, we store the position, size, color, and other attributes of every object drawn to the canvas. So, if you had a ball moving across the screen, each frame would store the position of the ball on that frame. Maybe frame 1 would indicate the ball is 10 pixels from the left side, frame 2 would indicate it’s 15 pixels, and so on. The code reads this data, draws the object according to the description given, and displays that frame. From that process, you can derive a flowchart, as shown in Figure 2-3.

Figure 2-3. Rendering and then displaying frames

BASICS OF JAVASCRIPT FOR ANIMATION

But when you consider how we described a dynamic, coded animation, the flowchart looks more like Figure 2-4.

Figure 2-4. Scripted animation

As you see in Figure 2-4, there is no concept of frame 1, frame 2, and so on. Programmed animation generally can, and usually does, all occur in just one frame. Here, you can start to see what we mean by a loop.

First, you set up an initial state, such as by drawing a circle to the screen using the built-in canvas drawing API. You then render and display the frame. Next, you apply your rules. The rules can be as simple as, “The ball will move 5 pixels to the right,” or they can be made up of dozens of lines of complex trigonometry. The examples in the book cover that entire spectrum. Applying the rules results in a new state—a new description that is then rendered and displayed. Then you apply the same rules all over again.

The same set of rules is applied over and over; you don’t have one set of rules for the first frame, and then another set for the next. So, your challenge is to come up with a set of rules that can handle every possible situation that can arise in your scene. What happens when the ball moves so far to the right that it’s off the canvas? Your set of rules needs to account for this. Do you want the user to interact with the ball using a mouse? Your rules need to take that into account as well.

It sounds daunting, but it’s not that complex. You start off with some simple behavior by creating a rule or two, and when that works, you add another rule. The “rules” we’ve been referring to are actually programming statements. Each rule can be a single statement or composed of several statements. In the example of moving the ball 5 pixels to the right, the rule is expressed in JavaScript like this:

ball.x = ball.x + 5;

This says to take whatever the ball’s x position (horizontal axis) is, add 5 to it, and make that its new x position. You can even simplify the expression like this:

ball.x += 5;

The += operator adds the value on the right to the variable on the left and assigns the result back to that variable.

Here’s a more advanced set of rules that you’ll see later in the book:

var dx = mouse.x – ball.x, dy = mouse.y – ball.y, ax = dx * spring, ay = dy * spring;