The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

Tips & Tools for Creating Interactive Web Application

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by igodigital, 2017-04-19 14:00:21

HTML5 Hacks

Tips & Tools for Creating Interactive Web Application

Keywords: html5,hack,tools,tips,interactive,web,applications

var canvas = document.getElementById("moveSmile");
var smileCtx = canvas.getContext("2d");

smileCtx.beginPath();

smileCtx.fillStyle = '#F1F42E';
smileCtx.arc(100,100,99,0,Math.PI*2); // head

smileCtx.stroke();
smileCtx.fill();

smileCtx.beginPath(); // Mouth
smileCtx.moveTo(170,100);
smileCtx.arc(100,100,70,0,Math.PI);
smileCtx.stroke();

smileCtx.beginPath(); // Left eye
smileCtx6.fillStyle = 'black';
smileCtx6.moveTo(60, 65);
smileCtx6.arc(60,65,12,0,Math.PI*2);
smileCtx6.fill();

smileCtx6.beginPath(); // Right eye
smileCtx6.moveTo(140,65);
smileCtx6.arc(140,65,12,0,Math.PI*2);
smileCtx6.fill();

Our code simply draws out this smiley face on the lefthand side of the <canvas> tag.
For illustration purposes, a 1 px border has been added to the <canvas> tag so that

we can see the boundaries (see Figure 4-15).

Going back to our three-step process, once we draw our illustration we need to erase
what we’ve drawn:

smileCtx.clearRect(0, 0, 800, 200); //smileCtx is the 2d context

For simplicity I’m erasing the whole canvas, but to optimize performance you should
focus on erasing what is changing for the next frame. In the preceding method I am

clearing the whole canvas by setting the clearRect coordinates from the top-

lefthand corner of the canvas to the bottom-righthand corner. This erases a rectan-
gular shape the size of the canvas.

Our canvas should now be void of illustration, as shown in Figure 4-16.

CHAPTER 4: HACKING YOUR GRAPHICS WITH CANVAS AND SVG 183

Figure 4-15.
The smiley face illustration on the lefthand side of an 800-point canvas

Figure 4-16.
The 800 × 200 <canvas> tag after the clearRect method has cleared the entire canvas context
184 HTML5 HACKS

Now, for step 3 we will redraw our smiley face, but we will move it slightly to the right.

In order to do this, we will move the x position of both our moveTo methods and our
element start position (arc in this case).

To accomplish this, we will replace each number with a simple equation to generate
the proper x coordinate each time the element is drawing:

x+startingposition

Our code will now look like this:

var x = 0;
smileCtx6.beginPath();

smileCtx6.fillStyle = '#F1F42E';
smileCtx6.arc(x+100,100,99,0,Math.PI*2); // head

smileCtx6.stroke();
smileCtx6.fill();

smileCtx6.beginPath(); // Mouth
smileCtx6.moveTo(x+170,100);
smileCtx6.arc(x+100,100,70,0,Math.PI);
smileCtx6.stroke();

smileCtx6.beginPath(); // Left eye
smileCtx6.fillStyle = 'black';
smileCtx6.moveTo(x+60, 65);
smileCtx6.arc(x+60,65,12,0,Math.PI*2);
smileCtx6.fill();

smileCtx6.beginPath(); // Right eye
smileCtx6.moveTo(x+140,65);
smileCtx6.arc(x+140,65,12,0,Math.PI*2);
smileCtx6.fill();

For the preceding code x is set to 0, but in order to move the smiley face across the
screen we need to change the x position. We’ll do this with a simple statement that
increases or decreases the x value appropriately (this will move it across the screen

and then back again).

There is one additional value we need to determine: the speed of the animation. If we
simply increment the value by 1, the smiley face will only move one pixel per iteration.

CHAPTER 4: HACKING YOUR GRAPHICS WITH CANVAS AND SVG 185

We want to put a little bit of pep in this animation, so we will create a new variable

called speed and set it to 6. When this number is added to the current x position, it

will move the smiley face forward or back six pixels, thus increasing the speed. Let’s
look at the code:

var speed = 6; //px it moves on each loop determines how fast it moves

x += speed;

if(x <= 0 || x >= 600){ //as far as we can go without cutting off
speed = -speed; //determines if it moves forwards or backwards;

}

Implementing requestAnimationFrame

As mentioned earlier, requestAnimationFrame is a new specification in the HTML5

family. It’s so new that most browsers only support a prefixed version of it. In order to
utilize it in modern browsers, we need to do a quick check to see which version of the
method we need to use, and then build a reference to it.

We will use the requestAnimationFrame method in our example to iterate through
our animation. To accomplish this, we will use it to call the same draw method cycli-
cally. Remember, the frame rate will be determined by requestAnimationFrame, as
it will call the draw method as soon as the browser is ready to draw another screen.

Putting It All Together

The requestAnimationFrame method is really the glue that holds this example to-

gether. To get everything working properly, we will set our variables at the top of our

page and then break our code into two methods. The first will determine the new x
value and then call the draw method.

The draw method will first clear the canvas from the previous frame and then draw

out the new frame. This method gets called over and over again. Our final code as-
sembles into this:

var x = 0;
var speed = 6; //px it moves on loop determines how fast it moves
var canvas = document.getElementById("moveSmile");
var smileCtx = canvas.getContext("2d");

function animate(){

reqAnimFrame = window.mozRequestAnimationFrame||window.webkitRequestAnima
tionFrame

186 HTML5 HACKS

||window.msRequestAnimationFrame||window.oRequestAnimationFrame
reqAnimFrame(animate);

x += speed;

if(x <= 0 || x >= 600){
speed = -speed; //see if it moves forwards or backwards;

}

draw();
}

function draw() {

smileCtx6.clearRect(0, 0, 800, 200);

smileCtx6.beginPath();

smileCtx6.fillStyle = '#F1F42E';
smileCtx6.arc(x+100,100,99,0,Math.PI*2); // head

smileCtx6.stroke();
smileCtx6.fill();

smileCtx6.beginPath(); // Mouth
smileCtx6.moveTo(x+170,100);
smileCtx6.arc(x+100,100,70,0,Math.PI);
smileCtx6.stroke();

smileCtx6.beginPath(); // Left eye
smileCtx6.fillStyle = 'black';
smileCtx6.moveTo(x+60, 65);
smileCtx6.arc(x+60,65,12,0,Math.PI*2);
smileCtx6.fill();

smileCtx6.beginPath();
smileCtx6.moveTo(x+140,65);
smileCtx6.arc(x+140,65,12,0,Math.PI*2); // Right eye
smileCtx6.fill();
}

animate();

CHAPTER 4: HACKING YOUR GRAPHICS WITH CANVAS AND SVG 187

Figure 4-17 shows a snapshot from our example. Our smiley face starts at the far-left
side of the canvas element, and then animates to the far-right side. It will then repeat
this step over and over again.

Figure 4-17.
A frame from the smiley face animation showing the smiley face moving from one side of the canvas
element to the other and back again

HACK 42 Build “Native” Illustrations with Scalable
Vector Graphics

Scalable Vector Graphics (SVG) is usually the most “familiar” graphics format in the
HTML5 family of technologies. This hack will quickly get you working with the SVG
format as though it were part of the DOM (hint: it really is part of the DOM!).
Scalable Vector Graphics is the W3C’s recommendation for web illustrations. Similar
to Flash, SVG is a markup language for describing two-dimensional vector graphics,
but it’s an open XML-based language as opposed to being proprietary. Think of SVG
as being the graphical equivalent to HTML, and like HTML, SVG works seamlessly with
other browser technologies such as JavaScript, CSS, and the DOM.

Why SVG?

Compared to all the other graphics and media-based technologies introduced in
HTML5, SVG has some major advantages. The primary advantage is the technology

188 HTML5 HACKS

itself. Being an XML-based language, SVG doesn’t require an editing program like
Flash, Photoshop, or even Paint. You can create and edit SVG images with any simple
text editor, or with your favorite web editor. The S in SVG stands for Scalable, and
scalable it is! SVG is resolution-independent. Your SVG images can be zoomed in or
out, and even printed at any size, and they will still maintain their quality, which is the
primary benefit of the technology.

Being pure XML, SVG is natively searchable, indexable, and easily compressible. It’s
also quite natural to embed text within your SVG files and then style them with CSS.
It’s also easy to make SVG graphics compliant with the Americans with Disabilities
Act (ADA), by embedding descriptions of the images within the SVG file itself.

Creating Your SVG Image

In most cases SVG is managed in its own file. This is a text-based file ending with .svg.
You would then embed that file into the DOM in a manner similar to how you would
work with an image. In our example, we’ll start with a new SVG file named smiley.svg
and embed it into our sample page with the following code:

<object data="smiley.svg" type="image/svg+xml" />

Technically, our SVG file is an object on the page, not an image, and therefore is em-
bedded with an object file. At this point we will see our object in the DOM, but it will
not display anything, as the SVG file is blank. But we will fix that.

Now, to really impress our friends and enemies we’ll build an SVG object that dem-
onstrates the cross-cultural symbol for love, peace, and hope: the smiley face.

Drawing with XML

Unlike a JPEG or PNG image, where the image is transmitted in Unicode, an SVG image
is drawn out by a series of rules that follow the XML schema. This tends to make the
images lightweight and ultra-scalable. In the preceding code example, we created an

object element that has a data attribute pointing to an SVG file. This SVG file contains

a few lines of code that draw out our smiley face. Before we start, let’s see how our
end product will look (see Figure 4-18).

This cheeky smiley face is truly simple. The SVG file consists of only five elements,
and each element becomes a discrete DOM element once it’s imported into the page.
As DOM elements, they follow all the same rules and have access to the same APIs as
all other page elements. Let’s take a quick look at each element comprising our smiley
face:

<circle cx="300" cy="164" r="160" fill="yellow" stroke="black"
stroke-width="2" />

CHAPTER 4: HACKING YOUR GRAPHICS WITH CANVAS AND SVG 189






















































































Click to View FlipBook Version