0% found this document useful (0 votes)
3 views37 pages

Advanced Graphics with SVG and Canvas

Creating Advanced Graphics

Uploaded by

valeriabuzz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

Advanced Graphics with SVG and Canvas

Creating Advanced Graphics

Uploaded by

valeriabuzz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

9/5/2014 Module 11: Creating Advanced Graphics

Module 11: Creating Advanced Graphics

Contents:

Module Overview

Lesson 1: Creating Interactive Graphics by Using SVG

Lesson 2: Drawing Graphics by Using the Canvas API

Lab: Creating Advanced Graphics

Module Review and Takeaways

Module Overview

High-resolution, interactive graphics are a key part of most modern applications. Graphics can help to enhance the user's
experience by providing a visual aspect to the content, making a website more attractive and easier to use. Interactivity enables
the graphical elements in a website to adapt and respond to user input or changes to the environment, and is another important
element in retaining the attention of the user and their interest in the content.

This module describes how to create advanced graphics in HTML5 by using Scalable Vector Graphics (SVG) and the Microsoft
Canvas API. You will learn how to use SVG-related elements such as <rect>, <ellipse>, and <polyline> to display graphical
content on a web page. You will also learn how to enable the user to interact with SVG elements through the use of events such
as keyboard events and mouse events.

The Canvas API is somewhat different than SVG. The Canvas API provides a <canvas> element and a set of JavaScript functions
that you can invoke to draw graphics onto the canvas surface. You will learn how to use the Canvas API, and also find out when it
is more appropriate to use Canvas or SVG.

Objectives

After completing this module, you will be able to:

• Use SVG to create interactive graphical content.

• Use the Canvas API to generate graphical content programmatically.

Lesson 1 : Creating Interactive Graphics by Using SVG

SVG is an XML grammar that has been incorporated into HTML. SVG enables you to incorporate interactive graphical content in
your web pages. SVG comprises a set of elements that you enclose in an <svg> element, and that become part of the Document
Object Model (DOM) for your web page.

Lesson Objectives

[Link] 1/37
9/5/2014 Module 11: Creating Advanced Graphics

After completing this lesson, you will be able to:

• Describe the elements of SVG.

• Create an <svg> element and embed simple graphical elements inside it.

• Use SVG to draw circles and ellipses.

• Use SVG to draw complex shapes.

• Apply fill styles and strokes to SVG elements.

• Use gradients and patterns to fill SVG elements.

• Use SVG to draw text.

• Apply transformations to SVG elements.

What is SVG?

SVG defines a set of elements that that represent common types of drawing shapes. For example, there are SVG-related elements
named <rect>, <text>, <ellipse>, <polygon>, and <path>. SVG implements two-dimensional vector graphics that scales to the
size of the user's browser window and the resolution of the screen on which it is running.

SVG uses a retained mode model. When you add SVG-related elements to an HTML5 web page, the elements are kept in the DOM
tree for the web page, and a user can interact with them in the same way as they would with HTML elements such as <h1>,
<div>, and <button>. As a developer, you can perform the following actions:

• Call DOM functions such as [Link]() and [Link]() to locate and manipulate SVG-
related elements in the document in JavaScript code.

• Apply CSS styles such as colors, borders, and transformations to SVG-related elements.

• Handle events such as mouse events and keyboard events on SVG-related elements. For example, you can use SVG to create a
complex graphical figure, and then handle mouse click events to enable the user to interact with specific elements within the
figure.

When you add SVG-related elements to your web page, the performance of the page depends on the number of elements. The
more elements you add, the more objects the browser has to create and add to the DOM tree, and the longer it will take the

[Link] 2/37
9/5/2014 Module 11: Creating Advanced Graphics

browser to render the page. If you want to create extremely complex graphical figures, the Canvas API might be a better option.

Creating SVG Graphics

To use SVG in a web page, add an <svg> element and specify an XML namespace as follows:

<svg xmlns="[Link]
...
</svg>

The <svg> element can contain any number of SVG-related elements, such as <rect> or <ellipse>. Each of these elements has a
set of properties that enable you to configure its appearance within the <svg> element. The following list describes some of the
common properties that you can set on SVG-related elements:

• x and y: The position of the shape within the <svg> element, relative to the left hand side and the top of the <svg> element,
respectively.

• width and height: The width and height of the shape.

• fill and stroke: The fill color and stroke color of the shape.

The following example creates an <svg> element that contains two rectangles. The first rectangle is red and has rounded corners,
as specified by the rx and ry attributes. The second rectangle is yellow, and partially obscures the first rectangle because it is
defined after it in the <svg> element:

<svg xmlns="[Link]
<rect x="50" y="50" width="100" height="75" rx="20" ry="20" fill="red" stroke="blue"
/>
<rect x="75" y="75" width="100" height="75" fill="yellow" stroke="blue" />
</svg>

The rectangles generated by this code look like this:

[Link] 3/37
9/5/2014 Module 11: Creating Advanced Graphics

FIGURE 11.1:RECTANGLES DRAWN BY USING AN <SVG> ELEMENT

You can define CSS styles for <svg> elements, and for the elements that are contained inside an SVG element. The following
example defines a style sheet rule for all <svg> elements. The rule specifies that all <svg> elements have a dark blue border, a
background color of light green, a width of 300 pixels, and a height of 200 pixels:

<style type="text/css">
svg {
border: 2px solid darkblue;
background-color: lightgreen;
width: 300px;
height: 200px;
}
</style>

The <svg> element from the previous example looks like this after the styling shown above is applied:

Drawing Circles and Ellipses

[Link] 4/37
9/5/2014 Module 11: Creating Advanced Graphics

SVG defines <circle> and <ellipse> elements that enable you to draw circles and ellipses in an <svg> element.

Circle

The <circle> element has cx and cy properties that specify the location of the center point for the circle inside the <svg>
element. <circle> also has an r attribute that specifies the radius of the circle.

The following example creates two circles. The first circle is red and the second circle is yellow. The second circle partially
obscures the first circle because it is defined after it in the <svg> element:

<svg xmlns="[Link]
<circle cx="120" cy="80" r="40" stroke="blue" fill="red" />
<circle cx="160" cy="120" r="60" stroke="blue" fill="yellow" />
</svg>

The circles generated by this code look like this:

FIGURE 11.3:CIRCLES DRAWN BY USING AN <SVG> ELEMENT

Ellipse

The <ellipse> element has cx and cy properties that specify the location of the center point. <ellipse> also has rx and ry
attributes that specify the radius of the ellipse in the X and Y directions. If rx and ry are the same, the ellipse will appear as a circle.

The following example creates two ellipses. The first ellipse is red and the second ellipse is yellow. The ellipses have the same
shape because they have the same rx and ry properties. However, the ellipses have different cy properties, so they appear at
different vertical offsets within the <svg> element:

[Link] 5/37
9/5/2014 Module 11: Creating Advanced Graphics

<svg xmlns="[Link]
<ellipse cx="150" cy="60" rx="110" ry="30" stroke="blue" fill="red" />
<ellipse cx="150" cy="140" rx="110" ry="30" stroke="blue" fill="yellow" />
</svg>

The ellipses generated by this code look like this:

FIGURE 11.4:ELLIPSES DRAWN BY USING AN <SVG> ELEMENT

Drawing Complex Shapes

SVG defines <polyline>, <polygon>, and <path> elements that enable you to draw complex shapes in an <svg> element.

Polyline
The <polyline> element creates a line drawing comprising a series of connected points. The points are specified by the points
attribute, which defines a comma-separated series of X and Y coordinates. A polyline does not connect the last point back to the
first point. The <polyline> element has various attributes such as stroke and fill, which enable you to configure the appearance of
the polyline.

The following example creates a polyline that draws a jagged blue line:

<svg xmlns="[Link]
<polyline points="105 100, 120 100, 125 90, 135 110, 145 90, 155 110, 165 90, 175
110, 180 100, 195 100" fill="none" stroke="blue" />
</svg>

[Link] 6/37
9/5/2014 Module 11: Creating Advanced Graphics

The polyline generated by this code looks like this:

FIGURE 11.5:POLYLINE DRAWN BY USING AN <SVG> ELEMENT

Polygon

The <polygon> element is similar to the <polyline> element, except that a polygon connects the last point back to the first point
to form a closed shape.

The following example creates a polygon that draws a yellow block arrow pointing upwards:

<svg xmlns="[Link]
<polygon points="110 70, 150 40, 190 70, 190 160, 150 130, 110 160" fill="yellow"
stroke="blue" />
</svg>

The polygon generated by this code looks like this:

FIGURE 11.6:POLYGON DRAWN BY USING AN <SVG> ELEMENT

Path
The <path> element enables you to draw a complex shape as a series of path segments. The <path> element has a d attribute
that defines the outline of the shape. The d attribute comprises a series of drawing commands as follows:

• M: Move to a new location, without drawing a line.

• L: Draw a line from the current location to a new location.

• A: Draw an elliptical arc.

• Q: Draw a quadratic Bezier curve. A quadratic Bezier curve is a curve that joins two points, and has one turning point along its
journey.

• C: Draw a cubic Bezier curve. A cubic Bezier curve is a curve that joins two points, and has two turning points along its journey.

[Link] 7/37
9/5/2014 Module 11: Creating Advanced Graphics

• Z: Close the current path by connecting the last point back to the first point.

The following example creates a simple path that draws a solid red triangle with a blue outline. The M command moves the
current location to (150, 50). The first L command draws a line from the current location to (250, 150). The next L command draws
a line from the current location to (50, 150). The Z command closes the path, by drawing a line back to the starting point of (150,
50):

<svg xmlns="[Link]
<path d="M 150 50 L 250 150 L 50 150 Z" fill="red" stroke="blue" />
</svg>

The filled path generated by this code looks like this:

FIGURE 11.7:FILLED PATH DRAWN BY USING AN <SVG> ELEMENT

Additional Reading: For more information about the <path> element, including details on how to draw arcs and
Bezier curves, see [Link]

Specifying Fill Styles and Stroke Styles

SVG-related elements have a series of attributes that enable you to specify how to fill an element and how to draw its outline.
These attributes include:

• stroke and fill: Specify the outline color and the fill color of the shape, respectively.

• stroke-opacity and fill-opacity: Specify the opacity of the outline and the filling of the shape, respectively. The opacity is a
fractional value between 0.0 and 1.0. A value of 0.0 means completely transparent, and a value of 1.0 means completely
opaque. The default

[Link] 8/37
9/5/2014 Module 11: Creating Advanced Graphics

opacity is 1.0.

• stroke-width: Specifies the width of the outline, either as an absolute size or as a percentage of the shape size.

• fill-rule: Specifies how to determine what side of a path is inside the shape. The fill-rule attribute is important in complex
overlapping shapes, because it enables SVG to determine which parts of the shape to fill with the fill color. There are two
possible values for fill-rule: nonzero and evenodd.

Additional Reading: For more information about fill rules, visit [Link]

• stroke-dasharray: Specifies a pattern of dashes and gaps to use when drawing the outline. The dasharray attribute is a series
of numbers specified by spaces or commas. The first number specifies the length of a dash; the second number specifies the
length of a gap; the third number specifies the length of the next dash; the fourth number specifies the length of the next gap;
and so on. Numbers can be expressed either as absolute values or as percentages.

The following example creates a rectangle with a black interior and no outline:

<svg xmlns="[Link]
<rect x="10" y="10" width="50" height="50" fill="black"/>

</svg>

The next example creates a rectangle with no interior and a light blue outline:

<svg xmlns="[Link]
<rect x="70" y="10" width="50" height="50" fill="none" stroke="lightblue"/>
</svg>

The next example creates a rectangle with a yellow interior and a thick, semi-transparent purple outline:

<svg xmlns="[Link]
<rect x="10" y="70" width="50" height="50"
fill="yellow"
stroke="purple"
stroke-width="5"
stroke-opacity="0.5" />
</svg>

The final example creates a rectangle with a semi-transparent yellow interior and a dashed purple outline:

<svg xmlns="[Link]

[Link] 9/37
9/5/2014 Module 11: Creating Advanced Graphics

<rect x="70" y="70" width="50" height="50"


fill="yellow"
fill-opacity="0.5"
stroke="purple"
stroke-width="2"
stroke-dasharray="2 2" />
</svg>

The following image shows the different fill and stroke styles generated by using these code examples:

FIGURE 11.1:FILL AND STROKE STYLES FOR SHAPES DRAWN BY USING AN <SVG> ELEMENT

Using Gradients and Patterns

SVG provides three elements that enable you to specify gradients and patterns that you can use to fill a shape or draw an outline:

• <linearGradient>

• <radialGradient>

• <pattern>

The following sections describe these elements in more detail.

The <linearGradient> Element


The <linearGradient> element creates a linear gradient of colors that can be applied to a shape. The <linearGradient> element
has four attributes to define the start and end locations of the linear gradient on the target shape:

• x1 and y1: Specifies the start point of the linear gradient on the target shape.

[Link] 10/37
9/5/2014 Module 11: Creating Advanced Graphics

• x2 and y2: Specifies the end point of the linear gradient on the target shape.

You can specify any number of color stops in a linear gradient. Each color stop is specified as a <stop> child element and has
two attributes:

• offset: Specifies the location of the color stop along the linear gradient.

• stop-color: Specifies the color to apply at this location along the linear gradient.

The following example shows how to define a linear gradient. The linear gradient starts at the top left corner of the shape to
which it is applied, because the x1 and y1 values are 0%. The linear gradient ends at the top right corner of the target shape,
because the x2 value is 100% and the y2 value is 0%. The linear gradient therefore defines a horizontal line across the top of the
target shape. There are three color stops that are applied along this line, creating a linear gradient that ranges from yellow to
green, and then from green to red:

<svg xmlns="[Link]
<linearGradient x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0.2" stop-color="yellow" />
<stop offset="0.5" stop-color="green" />
<stop offset="1.0" stop-color="red" />
</linearGradient>
</svg>

Note: A gradient is a reusable resource that you can apply to multiple shapes, as described in the section "Creating
Reusable Gradients and Patterns" later in this topic.

The following image shows this linear gradient applied to a rectangle:

FIGURE 11.2:A LINEAR GRADIENT APPLIED TO A RECTANGLE

The <radialGradient> Element

The <radialGradient> element creates a radial gradient of colors that can be applied to a shape. The <radialGradient> element
has two attributes named fx and fy that define the focal point of the radial gradient on the target shape.

You can specify any number of color stops in a radial gradient. Each color stop has offset and stop-color attributes; the offset

[Link] 11/37
9/5/2014 Module 11: Creating Advanced Graphics

attribute represents a percentage distance from (fx,fy) to the edge of the outermost circle.

The following example shows how to define a radial gradient. The radial gradient is focused on a point 30% from the top left
corner of the target shape, because the fx and fy values are 0.3. There are two color stops that are applied as concentric circles
centered on (fx, fy), creating a radial gradient that ranges from yellow to red:

<svg xmlns="[Link]
<radialGradient id="gradient2" fx="0.3" fy="0.3">
<stop offset="0.1" stop-color="yellow" />
<stop offset="0.7" stop-color="red" />
</radialGradient>
</svg>

The following image shows this radial gradient applied to a rectangle:

FIGURE 11.3:A RADIAL GRADIENT APPLIED TO A RECTANGLE

The <pattern> Element


The <pattern> element creates a pattern that can be applied to a shape. The <pattern> element has attributes that specify the
width and height of the pattern. The content to display in the pattern is specified as a child element of the <pattern> element.

The following example shows how to define a pattern based on an image file named "[Link]" which contains an image of the
Welsh flag.

<svg xmlns="[Link]
<pattern patternUnits="userSpaceOnUse" width="100" height="100">
<image xlink:href="[Link]" x="0" y="0" width="100" height="100" />
</pattern>
</svg>

Note: The patternUnits attribute controls how the image in a pattern is displayed. The value userSpaceOnUse causes
the image to be repeatedly tiled without any spacing.

The following image shows this pattern applied to a rectangle:

[Link] 12/37
9/5/2014 Module 11: Creating Advanced Graphics

FIGURE 11.4:A PATTERN APPLIED TO A RECTANGLE

Creating Reusable Gradients and Patterns


A web page might use a particular gradient or pattern at several different places. Rather than defining each gradient or pattern
separately, you can define them once within a <defs> element, and then refer to them by their id when you want to apply them
to elements in your page.

The following example defines three reusable gradients and patterns, and gives each one a unique id. The example then creates
several shapes. The shapes make use of the gradients and patterns by referencing their id values:

<svg xmlns="[Link]
<!-- Define some gradients and patterns, for use later -->
<defs>
<linearGradient id="gradient1" ... />
<radialGradient id="gradient2" ... />
<pattern id="wales" ... />
</defs>
<!-- Draw shapes that make use of the gradients and patterns -->
<polygon points="50,50 250,50 150,200" fill="url(#gradient1)" />
<ellipse cx="150" cy="50" rx="100" ry="20" fill="url(#wales)" />
<circle cx="150" cy="250" r="50" fill="url(#gradient2)" />
</svg>

The result of this code looks like this:

[Link] 13/37
9/5/2014 Module 11: Creating Advanced Graphics

FIGURE 11.5:PATTERNS AND GRADIENTS APPLIED TO A SET OF SHAPES

Drawing Graphical Text

SVG provides a <text> element that enables you to draw graphical text. You specify the text between the <text> start tag and
the </text> end tag.

SVG provides ways to customize the appearance of text:

• Text style.

• Text decorations.

• Text paths.

• Text span.

The following sections describe how to apply these customizations.

Text Style
The <text> element has a range of attributes that enable you to specify the text style. For example, you can set the fill, stroke,
and stroke-width attributes to define how the filling and outline for the text. You can also set the font-size, font-family, and
[Link] 14/37
9/5/2014 Module 11: Creating Advanced Graphics

font-weight attributes to specify the font for the text. The following example shows how to use these attributes:

<svg xmlns="[Link]
<text x="20" y="50"
fill="yellow" stroke="purple" stroke-width="2"
font-size="36" font-family="verdana" font-weight="bold">
Styled text
</text>
</svg>

The resulting text looks like this:

FIGURE 11.6:TEXT DRAWN AND STYLED BY USING THE <TEXT> ELEMENT OF AN <SVG> ELEMENT

Note: You can use gradients and patterns to fill text, using the techniques described in the previous topic, "Using
Gradients and Patterns"; just set the fill attribute to reference an appropriate gradient or pattern.

Text Decorations
The <text> element has a text-decoration attribute that takes a space-separated list of text decorations. The following text
decorations are supported:

• underline

• overline

• line-through

• blink

The following example shows how to set text decorations on <text> elements. The <text> elements are grouped inside a <g>
element. The <g> element enables you to group SVG shapes together and handle the result as though it were a single shape. In
this case, the <g> element defines a common set of styles and property values that apply to all <text> elements in the group:

<svg xmlns="[Link] id="decoratedText">


<g fill="yellow" stroke="purple" stroke-width="2" font-size="36" font-
family="verdana" font-weight="bold">
<text x="20" y="50">Normal text</text>
<text x="20" y="150" text-decoration="line-through">Text with line
through</text>
<text x="20" y="250" text-decoration="underline">Underlined text</text>
<text x="20" y="350" text-decoration="underline line-through">
Underlined text with line through

[Link] 15/37
9/5/2014 Module 11: Creating Advanced Graphics

</text>
</g>
</svg>

The text generated by this code looks like this:

FIGURE 11.7:TEXT DRAWN AND DECORATED BY USING THE <TEXT> ELEMENT OF AN <SVG> ELEMENT

Text Paths
A <text> element can contain a <textPath> child element that indicates a path to use as the baseline for the text when it is
displayed on the web page. For example, you can create a <textPath> that draws text around the perimeter of another shape on
the page.

The following example shows how to use <textPath>. In this example, a <path> element is created to represent a wavy line. The
<text> element has a <textPath> child element that links to the <path> element by using an XLink expression. An XLink
expression enables you to reference a fragment of XML or HTML code by using its identifier, as shown in the following example:

<svg xmlns="[Link] id="textPath">


<path id="wavyPath1"
fill="none" stroke="green" stroke-width="5"
d="M 50 250
C 150 150 250 50 350 150
C 450 250 550 350 650 250
C 750 150 850 150 850 150" />
<text font-size="46" fill="red" font-family="Verdana">
<textPath xlink:href="#wavyPath1">
Mae hen wlad fy nhadau yn annwyl i mi!
</textPath>
</text>

</svg>

The text and path drawn by this code looks like this:

[Link] 16/37
9/5/2014 Module 11: Creating Advanced Graphics

FIGURE 11.8:TEXT DRAWN BY USING TEXT PATH

Text Spans
A <textSpan> element can contain any number of <tspan> child elements that partition the text into a series of discrete
sections. Each section can be styled individually.

The following example shows how to partition a <text> element by using multiple <tspan> elements. The <tspan> elements
specify how to draw that particular part of text:

<svg xmlns="[Link] id="textSpans">


<defs>
<path id="wavyPath2"
d="M 50 250
C 150 150 250 50 350 150
C 450 250 550 350 650 250
C 750 150 850 150 850 150" />
</defs>
<text font-size="46" fill="orange" font-family="Verdana" stroke="purple">
<textPath xlink:href="#wavyPath2">
<tspan>Cubic equation: 5x</tspan>
<tspan dy="-30" fill="green" font-size="33">3</tspan>
<tspan dy="+30"> + 4x</tspan>
<tspan dy="-30" fill="green" font-size="33">2</tspan>
<tspan dy="+30"> + 6x - 5 = 0</tspan>
</textPath>
</text>
</svg>

The result looks like this (the path is the same as the previous example, but the text elements show a combination of font sizes
and fill colors):

FIGURE 11.9:TEXT CONSISTING OF SEVERAL <TSPAN> ELEMENTS


[Link] 17/37
9/5/2014 Module 11: Creating Advanced Graphics

Transforming SVG Elements

Transformations enable you to relocate, resize, rotate, and reshape an element. You can use transformations in conjunction with
JavaScript code to create animated graphics.

Transformations
To transform an element, set the transform attribute to one of the following values:

• rotate(angle, cx, cy): Rotates the shape by the specified angle, about the specified (cx, cy) center point.

• translate(dx, dy): Translates the shape by the specified distance in the X and Y directions.

• scale(sx, sy): Scales the shape by the specified fraction in the X and Y directions.

• skewX(angle): Skews the shape by the specified angle in the X direction.

• skewY(angle): Skews the shape by the specified angle in the Y direction.

Additional Reading: For more information about SVG transformations, visit [Link]
LinkID=267748.

You can apply multiple transformations on a shape by using nested <g> elements and then applying the transform attribute on
each shape. The following example shows how to perform multiple transformations on a rectangle. The example defines two
rectangles; the first rectangle is displayed without transformation, and the second rectangle is displayed with a translation, a
scaling of 0.5 to make it half the original size, and a rotation of 20 degrees about a center point of (160, 160):

<svg xmlns="[Link] id="transformations" >


<defs>
<pattern id="checkerPattern" width="80" height="80"
patternUnits="userSpaceOnUse">
<rect fill="red" x="0" y="0" width="40" height="40" />
<rect fill="blue" x="40" y="0" width="40" height="40" />
<rect fill="blue" x="0" y="40" width="40" height="40" />
<rect fill="red" x="40" y="40" width="40" height="40" />
</pattern>
</defs>

[Link] 18/37
9/5/2014 Module 11: Creating Advanced Graphics

<rect x="0" y="0" width="200" height="200" fill="url(#checkerPattern)"


stroke="orange" stroke-width="5" />
<g transform="translate(200, 200)">
<g transform="scale(0.5)">
<g transform="rotate(20, 160, 160)">
<rect x="0" y="0" width="200" height="200" fill="url(#checkerPattern)"
stroke="orange" stroke-width="5" />
</g>
</g>
</g>
</svg>

The rectangles drawn by this code look like this:

FIGURE 11.10:A RECTANGLE ROTATED, TRANSFORMED, AND SCALED BY USING AN <SVG> ELEMENT

Demonstration: Using SVG Transformations and Events


In this demonstration, you will see how to apply transformations to SVG elements, animate SVG elements, and handle events on
SVG elements.

Demonstration Steps
Transform SVG Elements

1. On the Windows 8 Start screen, click the Desktop tile.

2. On the Windows taskbar, click Internet Explorer.

3. In Internet Explorer, open the file E:\Mod11\Democode\[Link].

4. If a message box appears asking if you want to allow blocked content, click the Allow blocked content button.

[Link] 19/37
9/5/2014 Module 11: Creating Advanced Graphics

5. In Internet Explorer, click the Transformations button.

6. Right-click the web page in Internet Explorer, and then click View source.

7. In the source window, locate the <!-- Demonstrate transformations --> comment and review the <svg> element:

o The <transform> elements translate the square by 200 units in the X and Y axes, scale it by a factor of 0.5, and rotate it.

8. Close the source window.

Handle Events on SVG Elements

1. In Internet Explorer, click the Events button.

2. Hover the mouse over the red shape on the left side of the window. Verify that the shape changes to a yellow fill color and a
dotted green border.

3. Move the mouse off the shape. Verify that it reverts to a red fill color with no outline.

4. Hover the mouse over the blue shape on the right side of the window. Verify that the shape changes to a yellow fill color and
a dotted green border.

5. Move the mouse off the shape. Verify that it reverts to a blue fill color with no outline.

6. Click the red shape. Verify that a message box appears, indicating that the shape represents Alaska. Close the message box.

7. Click the blue shape. Verify that a message box appears, indicating that the shape represents Hawaii. Close the message box.

8. Right-click in the browser window, and then click View source.

9. In the source window, locate the <!-- Demonstrate events --> comment and review the <svg> element:

o The <path> elements contain the data that defines the two maps.

o Each <path> element responds to the onmousedown event and uses JavaScript code to display the appropriate
message.

10. In the source window, locate the path:hover CSS rule near the top of the document. This CSS rule defines the style for all
<path> elements when the user hovers over them with the mouse.

11. Close the source window.

12. Close Internet Explorer.

Lesson 2: Drawing Graphics by Using the Canvas API

The Canvas API comprises a <canvas> element and an associate set of JavaScript functions that enable you to draw shapes onto
the canvas. The Canvas API is an alternative to SVG graphics and is useful if you want to perform one-off graphical operations in
a web page. However, whereas SVG graphics are defined by using HTML5 elements, the Canvas API is programmatic and requires
you to draw graphics by writing JavaScript code.

Lesson Objectives
After completing this lesson, you will be able to:
[Link] 20/37
9/5/2014 Module 11: Creating Advanced Graphics

• Describe how the Canvas API works.

• Create a <canvas> element on a web page and use the Canvas API to draw simple shapes and lines.

• Use the Canvas API to draw complex shapes.

• Fill shapes by using gradients and patterns.

• Apply transformations and animations to canvas drawings.

What is the Canvas API?

The Canvas API enables you to draw graphical shapes onto a bitmap area on the web page. To use the Canvas API, you add a
<canvas> element to the page and then call JavaScript functions to draw shapes on the canvas drawing surface.

The Canvas API uses a "fire-and-forget" model. When you call JavaScript functions to draw shapes on a canvas, it is as if you are
painting shapes on a piece of paper. As soon as you have drawn the shapes, the drawing is complete. The shapes are not retained
in the DOM tree, so there is no way to interact with the shapes afterwards. For example, you cannot access shapes by using the
DOM, you cannot apply CSS styles to canvas shapes, and you cannot handle events on canvas shapes.

The performance of the Canvas API depends on the size and resolution of the device screen. The larger the device, and the higher
the resolution, the more pixels have to be painted and the slower the drawing will be rendered. If you want to create drawings
with comprise relatively few elements but that target large high-resolution devices, SVG might be a better option.

Using the Canvas API

[Link] 21/37
9/5/2014 Module 11: Creating Advanced Graphics

To use the Canvas API, the first step is to add a <canvas> element to your web page. You can also define a CSS style for
<canvas> elements, if required.

It is typical to define an id attribute on a <canvas> element, so that you can locate it easily in JavaScript code by calling a DOM
function such as [Link](). It is also quite common to define fallback content between the <canvas> start
tag and the </canvas> end tag; this content will be displayed by browsers that do not recognize the <canvas> element.

To draw graphics on a canvas, you must write JavaScript code. Follow these steps:

1. Get a reference to the <canvas> element by calling a DOM function such as [Link]().

2. Call getContext('2d') on the canvas object, to get the two-dimensional drawing context for the canvas.

3. Invoke methods in the context object, to draw shapes on the canvas surface.

The following example shows how to create a canvas and draw a rectangle on it. The example sets the [Link] property
to set the ambient fill color to red for subsequent drawing operations. The example then calls the [Link]() method to
draw a solid rectangle. The rectangle will be filled with the ambient fill color, which is red. The canvas itself has a dark blue border
and a light green fill color, due to the CSS style rule at the top of the code:

<style>
canvas {
border: 2px solid darkblue;
background-color: lightgreen;
}
</style>

<h1>Getting started with canvas</h1>
<canvas id="myCanvas">No canvas support in this browser</canvas>
<script>
var canvas = [Link]('myCanvas');
var context = [Link]('2d');
[Link] = "red";
[Link](20, 20, [Link] - 40, [Link] - 40);
</script>

The rectangle drawn by this code look like this:

[Link] 22/37
9/5/2014 Module 11: Creating Advanced Graphics

FIGURE 11.11:A RECTANGLE DRAWN BY USING THE CANVAS API

Note that the Canvas API also provides a [Link]() function that draws the outline of a rectangle but does not fill its
interior.

The Canvas API has a range of functions for drawing shapes and lines, including:

• arc() and arcTo(): Draw an arc.

• quadraticCurveTo(): Draw a quadratic Bezier curve.

• bezierCurveTo(): Draw a cubic Bezier curve.

Additional Reading: For more information about the full set of functions available in a canvas two-dimensional
context, see [Link]

Drawing Paths

You can draw complex shapes by using a path. The Canvas API has a beginPath() function that enables you to create a path
connecting a series of points. You can then call functions such as moveTo() and lineTo() to move to new locations, and
optionally you can call closePath() to connect the final point back to the first point.

When you are ready to render the path, you can call the stroke() function to draw the outline of the path. You can also call the
fill() function to draw the interior of the path.

[Link] 23/37
9/5/2014 Module 11: Creating Advanced Graphics

The following example shows how to draw a triangle path by using the Canvas API. The triangle has a blue outline color, because
the strokeStyle property is set to rgb(0, 0, 255). The triangle has a semi-transparent red fill color, because the fillStyle property
is set to rgba(255, 0, 0, 0.75).

<canvas id="myCanvas">
Sorry, your browser does not support canvas.
</canvas>
<script>
// Get the canvas element and its drawing context.

var canvas = [Link]('myCanvas');


var context = [Link]('2d');
// Clear any existing content in the canvas.
[Link](0, 0, [Link], [Link]);
// Set the stroke color and the fill color.
[Link] = "rgb(0, 0, 255)";
[Link] = "rgba(255, 0, 0, 0.75)";
// Create a path in absolute coordinates.
[Link]();
[Link](60, 30);
[Link](100, 90);
[Link](20, 90);
// Close the path.
[Link]();
// Draw the path as a stroked shape;
[Link]();
// Draw the path as a filled shape.
[Link]();
</script>

The triangle drawn by this code looks like this:

FIGURE 11.12:A TRIANGLE DRAWN BY USING THE CANVAS API

Using Gradients and Patterns

[Link] 24/37
9/5/2014 Module 11: Creating Advanced Graphics

The Canvas API provides functions that enable you to specify gradients and patterns that you can use to fill a shape or draw an
outline:

• createLinearGradient()

• createRadialGradient()

• createPattern()

The following sections describe these functions in more detail.

The createLinearGradient() Function


The createLinearGradient() function creates a linear gradient. createLinearGradient() has parameters that define the start and
end locations of the linear gradient, and returns a linear gradient object. You can add color stops to the linear gradient by calling
the addColorStop() function. You can then set the linear gradient as the ambient fill style or stroke style for a canvas context, by
setting the fillStyle or strokeStyle property. You can also use the gradient to define the fill color or the stroke color for text.

The createRadialGradient() Function


The createRadialGradient() function creates a radial gradient. createRadialGradient() has parameters that define the focal point
of the radial gradient. You can add color stops to the gradient and apply it to a context in the same way that you would for a
linear gradient.

The createPattern() Function


The createPattern() function creates a pattern, typically based on an image or some other content on the web page. You can
apply a pattern in the same way that you would for a linear gradient or a radial gradient.

The following example shows how to create a linear gradient, a radial gradient, and a pattern. The pattern used is based on the
wales image (this image is the flag of Wales in the United Kingdom).

<canvas id="myCanvas">
Sorry, your browser doesn't support canvas.
</canvas>
<img id="wales" src="[Link]" style="display: none;" />
<script>

[Link] 25/37
9/5/2014 Module 11: Creating Advanced Graphics

// Get the canvas element and its drawing context.


var canvas = [Link]('myCanvas');
var context = [Link]('2d');
[Link] = 5;
demoLinearGradient();
demoRadialGradient();
demoPattern();
function demoLinearGradient()
{
var linearGradient = [Link](0, 0, 0, [Link]);
[Link](0, "red");
[Link](0.4, "yellow");
[Link](1, "green");
drawShapes(linearGradient);
}
function demoRadialGradient()
{
var radialGradient = [Link]([Link]/2, [Link]/2,
10, [Link]/2, [Link]/2, 100);
[Link](0, "red");
[Link](0.4, "yellow");
[Link](1, "green");
drawShapes(radialGradient);
}
function demoPattern()
{
var image = [Link]("wales");
var pattern = [Link](image, "repeat");
drawShapes(pattern);
}
function drawShapes(theStyle)
{
// Clear any existing content in the canvas.
[Link](0, 0, [Link], [Link]);
// Draw a filled triangle, using the specified style.
[Link] = theStyle;
[Link] = "rgb(200, 200, 200)";
[Link]();
[Link](70, 30);
[Link](130, 140);
[Link](10, 140);
[Link]();
[Link]();
[Link]();
// Draw a stroked circle, still using the specified style.
[Link]();
[Link]([Link]/2, [Link]/2, 50, 0, 2*[Link]);
[Link]();

[Link] 26/37
9/5/2014 Module 11: Creating Advanced Graphics

// Draw a stroked triangle, using the specified style.


[Link] = "rgb(200, 200, 200)";
[Link] = theStyle;
[Link]();
[Link](230, 30);

[Link](290, 140);
[Link](170, 140);
[Link]();
[Link]();
[Link]();
}
</script>

The shapes generated by this code look like this:

FIGURE 11.13:SHAPES FILLED WITH A PATTERN FROM AN IMAGE FILE

Transforming Shapes

The Canvas API enables you to transform the coordinates of the canvas context so that subsequent drawing operations are
performed on a transformed coordinate system. To use transformations in the Canvas API, use the following functions:

• rotate(angle): Rotates the coordinate system by the specified angle clockwise in radians.

• translate(dx, dy): Translates the coordinate system by the specified distance in the X and Y directions.

• scale(sx, sy): Scales the coordinate system by the specified fraction in the X and Y directions.

• transform(scaleX, skewX, scaleY, skewY, translateX, translateY): Adjusts the current transformation matrix to perform

[Link] 27/37
9/5/2014 Module 11: Creating Advanced Graphics

scaling, skewing, and translation.

• setTransform(scaleX, skewX, scaleY, skewY, translateX, translateY): Sets a new transformation matrix to perform scaling,
skewing, and translation.

Additional Reading: For more information about Canvas transformations, visit [Link]
LinkID=267750.

Demonstration: Performing Transformations by Using the Canvas API


In this demonstration, you will see how use transformations to rotate, skew, and translate graphics.

Demonstration Steps

Perform Simple Transformations

1. On the Windows 8 Start screen, click the Desktop tile.

2. On the Windows taskbar, click Internet Explorer.

3. In Internet Explorer, open the file E:\Mod11\Democode\[Link].

4. If a message box appears asking if you want to allow blocked content, click the Allow blocked content button.

5. In Internet Explorer, click the Separate Transformations button.

6. Right-click the web page in Internet Explorer, and then click View source.

7. In the source window, locate the demoSeperateTransformations function and review the code:

o The demoSeperateTransformations function uses the drawShape function to draw a triangle filled with an image of
the Welsh flag.

o Before calling the drawShape function, the code transforms the context; it moves the canvas to the right and down by
half the width and height of the canvas, then it scales the context by a different value in the X and Y dimensions, and
then rotates the context by PI/4 radians.

o When the drawShape function is called, the image is transformed according to the context settings.

Note: If time allows, comment out each of the transformations and run the code again. Then uncomment
each transformation one at a time, so that students can see the effects of each one.

Perform Matrix Transformation

1. In Internet Explorer, click the Matrix Transformations button.

2. In the source window, locate the demoMatrixTransformations function and review the code:

o This function is similar to the previous one in that it transforms the context and then calls the drawShape function to
display the image.

[Link] 28/37
9/5/2014 Module 11: Creating Advanced Graphics

o The difference is that this function uses the transform function to perform a matrix transformation, scaling, skewing,
and translating the context in a single function call.

3. Close the source window.

4. Close Internet Explorer.

Demonstration: Creating Advanced Graphics


In this demonstration, you will learn about the tasks that you will perform in the lab for this module.

Lab: Creating Advanced Graphics

Scenario

The conference organizers would like a venue map displayed on the website. Conference attendees will use the map to find out
more about the rooms of the conference facility. Therefore, the map should be interactive, responding to mouse clicks. The floor
plans are available in a vector format, so they can be displayed in a resolution-independent format.

Conference speakers need badges with their photo, name, and ID. The ID is in the form of a barcode to make it easy for security
personnel to scan and verify the holder’s identity before allowing backstage access. You have been asked to create a web page
that enables a speaker to create a badge.

Objectives

After completing this lab, you will be able to:

• Create graphics by using SVG, interactively style SVG graphics, and handle SVG graphics events.

• Draw graphics by using the Canvas API.

Estimated Time: 60 minutes

• Virtual Machines: 20480B-SEA-DEV11, MSL-TMG1

• User Name: Student

• Password: Pa$$w0rd

Exercise 1: Creating an Interactive Venue Map by Using SVG

Scenario

In this exercise, you will create an interactive conference venue map.

First, you will complete the partially completed SVG mark-up of the venue map. Next, you will add interactive styling to the SVG
by using CSS. Then you will handle SVG element click events to display extra information about conference rooms. Finally, you
will run the application, view the Location page, and verify that the venue map is interactive.

[Link] 29/37
9/5/2014 Module 11: Creating Advanced Graphics

The main tasks for this exercise are as follows:

1. Review the incomplete HTML markup for the venue map.

2. Complete the SVG venue map.

3. Add interactivity to the venue map.

4. Test the application.

Task 1: Review the incomplete HTML markup for the venue map

1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20480B-SEA-DEV11 virtual machine if it is not already running, and log on as Student with the password
Pa$$w0rd.

3. Start Visual Studio and open the [Link] solution in the E:\Mod11\Labfiles\Starter\Exercise 1 folder.

4. Open the [Link] file.

5. Verify that the page contains the following <svg> element of the venue map, and two hidden <div> elements containing
room information:

<svg viewBox="-1 -1 302 102" width="100%" height="230">


<!-- Room A -->
<g id="room-a" class="room">
<rect fill="#fff" x="0" y="0" width="100" height="100"/>
<text x="13" y="55" font-weight="bold" font-size="20">ROOM A</text>
</g>
<!-- Room B -->
<!-- The outline of the building -->
<polyline fill="none" stroke="#000" points="135,95 140,100 0,100 0,0 100,0 100,80
130,80 130,70 110,70 110,30 190,30 190,70 170,70 170,80 200,80 200,0 300,0 300,100
160,100 165,95"/>
<text x="150" y="55" font-size="12" style="text-anchor:
middle">Registration</text>
</svg>

Also notice that the script references the [Link] script in the scripts/pages folder:

<script src="/scripts/pages/[Link]" type="text/javascript"></script>

6. Run the application and view the Location page. Notice that the details for Room B are missing:

The venue map currently looks like this:

[Link] 30/37
9/5/2014 Module 11: Creating Advanced Graphics

FIGURE 11.1:THE INCOMPLETE VENUE MAP

7. Close Internet Explorer.

Task 2: Complete the SVG venue map

1. In the [Link] file, add the SVG elements for Room B by using room-b as the group element id. The missing elements
are a filled rectangle and the text with the name of the room. Use the SVG elements for Room A as a guide.

Note: You may need to view the page in Internet Explorer and experiment with the coordinate values to get
elements in the correct location.

Task 3: Add interactivity to the venue map

1. The venue map should be interactive; a user should be able to view more information about a room by clicking on it in the
map. In the [Link] file, find the following <div> elements. These elements contain the information about each room,
but they are hidden by default:

<div id="room-a-info" style="display: none">


<h2>Room A</h2>
<p>Capacity: 250</p>
<p>Popular sessions in here:</p>
<ul>
<li>Diving in at the deep end with Canvas</li>
<li>Real-world Applications of HTML5 APIs</li>
<li>Transforms and Animations</li>

[Link] 31/37
9/5/2014 Module 11: Creating Advanced Graphics

</ul>
</div>
<div id="room-b-info" style="display: none">
<h2>Room B</h2>
<p>Capacity: 230</p>
<p>Popular sessions in here:</p>
<ul>
<li>Building Responsive UIs</li>
<li>Getting to Grips with JavaScript</li>
<li>A Fresh Look at Layouts</li>
</ul>
</div>

2. Notice that each <div> is named after the room with the suffix –info.

Note: The information for each room is hard-coded into the HTML markup. However, to make the page even
more dynamic, you could retrieve information about popular sessions from the web service used in the Schedule
page.

3. The room should change color when the mouse moves over it. Open the [Link] style sheet in the styles\pages folder.
This style sheet contains CSS for the [Link] page.

4. Add a CSS rule that targets rect elements when the cursor is hovering over .room elements.

5. In this rule, set the fill property to #b1f8b0

6. Open the [Link] file in the scripts\pages folder. This JavaScript file contains the showRoomInfo function that
displays information about a room. The id of the room is specified as the parameter to this function.

7. Add click event listeners for the SVG room elements, which call the showRoomInfo function.

o After the comment // TODO: Get the room elements in the svg element, use the querySelectorAll function of the
document object to find all elements that have the class set to .room and assign them to the rooms variable.

o After the comment // TODO: Add a click event listener for each room element, iterate through the list of elements in
the rooms variable and add the click event handler for each item.

Task 4: Test the application

1. Run the application and view the [Link] page.

2. Move the cursor over each room and verify that the fill color changes.

The venue map should look like this:

[Link] 32/37
9/5/2014 Module 11: Creating Advanced Graphics

FIGURE 11.2:THE VENUE MAP WITH ROOM A HIGHLIGHTED

3. Click each room and verify that the correct information is displayed next to the venue map.

The information displayed for Room B should look like this:

FIGURE 11.3:THE DETAILS FOR ROOM B

4. Close Internet Explorer.

Results: After completing this exercise, you will have a venue map that displays extra information when clicked.

Exercise 2: Creating a Speaker Badge by Using the Canvas API

Scenario

In this exercise, you will use the Canvas API to draw the elements of a conference speaker’s badge.

First, you will create a canvas element on the speaker badge page. Next, you will write JavaScript code to implement methods
that draw parts of the badge. Finally, you will run the application and test the speaker badge page.

The main tasks for this exercise are as follows:

1. Create the canvas element.

2. Draw the details for the badge.

3. Test the application.

[Link] 33/37
9/5/2014 Module 11: Creating Advanced Graphics
Task 1: Create the canvas element

1. In Visual Studio, open the [Link] solution in the E:\Mod11\Labfiles\Starter\Exercise 2 folder.

2. Open the [Link] file. This page contains a section that enables the user to create their speaker badge.
Previously, you used an <img> element to drag and drop an image of the speaker onto this page. This <img> element has
been removed because you are going to modify the page to use a canvas instead. Using a canvas provides more scope for
customizing the image.

3. Find following comment:

<!-- TODO: Add canvas here -->

4. Add a <canvas> element, with a width of 500 and a height of 200 after the comment.

5. Add a solid black border to the canvas by using a CSS style. Set the width to 1px.

6. Add the following custom attributes to the canvas element:

data-speaker-id="234724"
data-speaker-name="Mark Hanson"

Note: The custom data attributes provide a convenient way to store application-specific data in an HTML
element. They will be used by the JavaScript code that draws the elements for the badge on the canvas.
In this exercise, these details are hard-coded into the HTML markup, but you could also write JavaScript code to
dynamically populate these attributes.

Task 2: Draw the details for the badge

1. Open [Link] file in the scripts\pages folder. The JavaScript code in this file contains a refactored version of the
drag-and-drop code that you created during an earlier lab exercise. Notice that the canvas element on the page has been
assigned to [Link]:

[Link] = [Link]("canvas");

The file also contains a number of other functions that will draw the various elements of the speaker's badge.

Note: The other drawing methods of the speaker badge page object will use the context, assigned to [Link], to
do their drawing.

2. In the drawBadge method after the comment // TODO: Get the canvas's ([Link]) context and assign to [Link],

[Link] 34/37
9/5/2014 Module 11: Creating Advanced Graphics

assign [Link] to be the canvas’s 2D context.

3. After the comment // TODO: Draw the following by calling the helper methods of `this`, add code to perform the following
tasks:

• Draw the background (use the drawBackground function).

• Draw the top text (use the drawTopText function; this function simply generates the text ContosoConf 2012 Speaker, which
is displayed at the top of the badge).

• Draw the speaker name (use the drawSpeakerName function).

• If the image variable references a valid image, then draw the speaker's image (use the drawSpeakerImage function and pass
the image variable as the parameter), otherwise draw a placeholder (use the drawImagePlaceHolder function).

• Draw the bar code (use the drawBarCode function and pass the value in the speakerId variable as the parameter).

4. In the drawBackground method, after the comment // TODO: Fill the canvas with a white rectangle, add statements to fill
the canvas with a white rectangle.

o Set the fillStyle of the context to "white".

o Use the fillRect method of the context to draw and fill the rectangle; the width and height properties of the rectangle
should be the same as those of the canvas.

5. In the drawSpeakerImage method, after the comment // TODO: Draw the image on the canvas, add code to draw the
image on the canvas at the coordinates (20, 20), with size 160 × 160.

o Use the drawImage method of the context.

o Note that the image is not always square, so calculate the source coordinates and size that will display the central
square portion only. Use the [Link] function to calculate the minimum of the image’s width and height properties,
like this:

var size = [Link]([Link], [Link]);

The following image highlights the central square portion of a rectangle.

FIGURE 11.4:THE CENTRAL SQUARE PORTION OF A RECTANGLE

[Link] 35/37
9/5/2014 Module 11: Creating Advanced Graphics

6. In the drawSpeakerName method, after the comment // TODO: Draw [Link] on the canvas, add code to draw
the speaker's name on the canvas:

o The speaker’s name is available in the [Link] property.

o Configure the following properties of the canvas to style the text before drawing it.

i. font: 40px sans-serif.

ii. fillStyle: black.

iii. textBaseline: top.

iv. textAlign: left.

v. fillText: the speaker's name.

Task 3: Test the application

1. Run the application and view the [Link] page.

2. Drag and drop the [Link] image file from the E:\Mod11\Labfiles\Resources folder onto the canvas.

3. Verify that the image is drawn on the canvas, along with the speaker’s details.

The speaker badge should look like this:

FIGURE 11.5:THE SPEAKER BADGE FOR MARK HANSON

4. Close Internet Explorer.

Results: After completing this exercise, you will have a Speaker Badge page that enables a conference speaker to create their
badge.

Module Review and Takeaways

In this module, you have seen how to use SVG and the Canvas API to draw graphical content in a web page.
[Link] 36/37
9/5/2014 Module 11: Creating Advanced Graphics

SVG uses a retained drawing model, which means SVG elements are retained in the DOM tree. You can access SVG elements by
using DOM functions, you can style SVG elements by using CSS style rules, and you can handle user-interaction events on SVG
elements.

The Canvas API uses a fire-and-forget drawing model, which means shapes are drawn on the canvas but are not retained in the
DOM tree. You cannot access shapes in a canvas by using DOM functions, or style the shapes, or handle any events on them.
Nonetheless, the Canvas API is very useful if you need to draw static graphical images on the web page.

Review Question(s)

Test Your Knowledge

Question

Which of the following statements about SVG is false?

Select the correct answer.

You can use SVG to draw complex shapes, and fill them with gradients and patterns.

SVG elements are parsed by the browser when the page is first loaded, and they are then discarded from memory.

You can create SVG elements dynamically by using DOM functions such as [Link]().

You can handle events on SVG elements.

SVG elements must be enclosed in an <svg> container element on a web page.

Question: When might you consider using the Canvas API instead of using SVG?

[Link] 37/37

You might also like