Advanced Graphics with SVG and Canvas
Advanced Graphics with SVG and Canvas
Contents:
Module Overview
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
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
• Create an <svg> element and embed simple graphical elements inside it.
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.
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.
• 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>
[Link] 3/37
9/5/2014 Module 11: Creating Advanced Graphics
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:
[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>
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>
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
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>
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:
• 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>
Additional Reading: For more information about the <path> element, including details on how to draw arcs and
Bezier curves, see [Link]
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
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
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>
• 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 <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 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.
[Link] 12/37
9/5/2014 Module 11: Creating Advanced Graphics
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>
[Link] 13/37
9/5/2014 Module 11: Creating Advanced Graphics
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.
• Text style.
• Text decorations.
• Text paths.
• Text span.
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>
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:
[Link] 15/37
9/5/2014 Module 11: Creating Advanced Graphics
</text>
</g>
</svg>
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>
The text and path drawn by this code looks like this:
[Link] 16/37
9/5/2014 Module 11: Creating Advanced Graphics
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:
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):
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.
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):
[Link] 18/37
9/5/2014 Module 11: Creating Advanced Graphics
FIGURE 11.10:A RECTANGLE ROTATED, TRANSFORMED, AND SCALED BY USING AN <SVG> ELEMENT
Demonstration Steps
Transform SVG Elements
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
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.
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.
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.
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
• Create a <canvas> element on a web page and use the Canvas API to draw simple shapes and lines.
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.
[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>
[Link] 22/37
9/5/2014 Module 11: Creating Advanced Graphics
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:
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.
[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 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
[Link] 26/37
9/5/2014 Module 11: Creating Advanced Graphics
[Link](290, 140);
[Link](170, 140);
[Link]();
[Link]();
[Link]();
}
</script>
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
• 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 Steps
4. If a message box appears asking if you want to allow blocked content, click the Allow blocked content 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.
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.
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
• Create graphics by using SVG, interactively style SVG graphics, and handle SVG graphics events.
• Password: Pa$$w0rd
Scenario
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
Task 1: Review the incomplete HTML markup for the venue map
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.
5. Verify that the page contains the following <svg> element of the venue map, and two hidden <div> elements containing
room information:
Also notice that the script references the [Link] script in the scripts/pages folder:
6. Run the application and view the Location page. Notice that the details for Room B are missing:
[Link] 30/37
9/5/2014 Module 11: Creating Advanced Graphics
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.
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:
[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.
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.
2. Move the cursor over each room and verify that the fill color changes.
[Link] 32/37
9/5/2014 Module 11: Creating Advanced Graphics
3. Click each room and verify that the correct information is displayed next to the venue map.
Results: After completing this exercise, you will have a venue map that displays extra information when clicked.
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.
[Link] 33/37
9/5/2014 Module 11: Creating Advanced Graphics
Task 1: Create the canvas element
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.
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.
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.
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
3. After the comment // TODO: Draw the following by calling the helper methods of `this`, add code to perform the following
tasks:
• 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).
• 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 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 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:
[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 Configure the following properties of the canvas to style the text before drawing it.
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.
Results: After completing this exercise, you will have a Speaker Badge page that enables a conference speaker to create their
badge.
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)
Question
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]().
Question: When might you consider using the Canvas API instead of using SVG?
[Link] 37/37