1. Trang chủ
  2. » Công Nghệ Thông Tin

XML in 60 Minutes a Day phần 7 docx

72 189 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề XML in 60 Minutes a Day
Trường học University of Example
Chuyên ngành Computer Science
Thể loại Bài viết
Năm xuất bản 2025
Thành phố Example City
Định dạng
Số trang 72
Dung lượng 9,53 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The value gemdata provides the subsequent data island with a data source reference that will be used later in the file.. respec-Lab 10.2: XHTML File Containing a Reference to an External

Trang 1

exercise is simple and fast, and you won’t have to do a lot of typing Onceyou see how it works and that it works, you will actually own a func-tioning example of this kind of data file You can copy and modify thisfile to create more of them

1. Download the file called gemsB_IDI.htm from the Chapter 10 page

of the XML in 60 Minutes a Day Web site, as described in this book’s

introduction, and put the file in the C:\WWW\SpaceGems directory.The _IDI has been inserted into the filename to remind you that itcontains an internal XML data island

2. Test the gemsB_IDI.htm file in the browser to make sure that itworks There is no link to this particular file yet, so you must enterthe filename as part of the URL (don’t forget the underscore betweenthe B and the IDI) In the browser’s locator bar, type:

http://localhost/spacegems/gemsB_IDI.htm

3. When the file is displayed, it should look like Figure 10.15

4. Using HTML-Kit, open the gemsB_IDI.htm file

5. Using the following steps as a guide, examine the content of thegemsB_IDI.xml file:

a. Note that the actual XML data instance is situated between theHTML <head> tags

b. Look closely at the <xml id=”gemdata”> opening and </xml>closing tags This element type can only be named <xml> It indi-cates to the browser’s parser that the information between thestart and end tags is the data island If you were to change theelement name from <xml> to <xmla>, for example, it would notwork

c. The id attribute defined inside the <xml id=”gemdata”> start tag

is also mandatory The value gemdata provides the subsequent

data island with a data source reference that will be used later

in the file

d. Now examine the HTML <table> element start tag in the following:

<table border=”1” width=”100%”

summary=”Space Gems Quick List of Details”

datasrc=”#gemdata”>

e. The datasrc=”#gemdata” attribute binds the data source fied by the id attribute mentioned in Step c.) to the HTML table.This attribute therefore designates the HTML table as a data consumer

Trang 2

(speci-Figure 10.15 Displaying the gemsB_IDI.htm file.

f. You must include a pound sign (#) as the first character of thevalue specified for the datasrc attribute

g. Every table must have table data <td> tags that define the individual cells where data is to be displayed

h. You must define the <div> tag Refer to the chapter notes foralternatives The datafld=”name” attribute inside the <divdatafld=”name” /> element tag (which is nested within the <tdalign=”left” > </td> tags) binds the value of name= attribute tothat table cell

i. The rest of the code is similar and binds more table cells to tive <gem> elements and the values of their attributes Beyondthat, several regular HTML tags specify display formats for thevarious elements

respec-Lab 10.2: XHTML File Containing a Reference to an External Data Island

With two quick changes, you can morph the internal data island in the firstexample data file into a reference to an external data source or external data

Trang 3

island After you make the changes to your XHTML file, we’ll provide analready created data file named gemsB.xml as the data source.

In a situation where you have a small Web site without a lot of data,you may not need a sophisticated database Keeping your data insideexternal XML files like gemsB.xml is sufficient (Incidentally, it is no coin-cidence that the data in that file is identical to the data found in the inter-nal data island example.)

1. If you do not already have a fully functional gemsB.xml data file,you can download a new copy from the Chapter 10 page of the

XML in 60 Minutes a Day Web site.

2. Using HTML-Kit, open the gemsB_IDI.htm file

3. Before you begin modifying this file, save it as gemsB_EDI.htm tothe C:\WWW\SpaceGems directory The EDI in the filename isintended to remind you that this document will contain the refer-ence to the external data island

4. Delete all the code nested within the <xml id=”gemdata”> and

</xml> tags, including the <xml id=”gemdata”> and </xml> tagsthemselves

5. Replace the deleted code with the following new <xml> tag, whichcontains the reference to the external data island file named

gemsB.xml:

<xml id=”gemdata” src=”gemsB.xml” />

6. Check to make sure that this new <xml> tag is situated between the

<head> and <title> elements

7. Replace the word Internal with External inside the <title> tag

8. Save the modified file

9. Test the gemsB_EDI.htm file in the browser to make sure that itworks Because there is no link to this particular file yet, you mustenter the filename as part of the URL in the browser’s locator bar.(Don’t forget to include the underscore between the B and the EDI

in the filename.)

http://localhost/SpaceGems/gemsB_EDI.htm

When displayed, the file should once again look like Figure 10.15

10. So that you won’t have to keep entering the filename as part of theURL, modify the existing Quick List of Diamonds hyperlink on theindex.html file To do this:

a. Using HTML-Kit, open the index.html file

b. Change the code for the link from

Trang 4

<a href=”gems1.xml”>Quick List of Diamonds</a>

to

<a href=”gemsB_EDI.htm”>Quick List of Diamonds</a>.

11. Save the file back as index.html

12. Test the link on the index.html file in the browser to make sure that

it works Type the following into the browser’s locator bar:

http://localhost/SpaceGems/

13. When the index/home page appears, click the Quick List of Diamonds hyperlink The successful display should look like Figure 10.15

Lab 10.3: JavaScript Using Internet Explorer’s

DSO Binding Technology

This is a slightly more advanced lab, but we won’t let it get too farbeyond you Whether or not you understand and use JavaScript regu-larly, this lab should interest you and perhaps stimulate your creativity

In it, we show you how to create and bind data, then how to navigate it

on your local system, without having to enlist the original Web server torecast and retransmit the data In a situation where you have a small Website with little data, you may not need a database at all Keeping yourdata inside an external XML file is just fine This data may even beexported from a larger database, in which the XML file is just a temporarystore

Four basic steps make up this JavaScript lab exercise:

■■ Creating the data island

■■ Binding the data fields

■■ Creating a JavaScript navigation mechanism

■■ Testing the catalog.htm Web page

Please note that this lab is a Microsoft-specific solution.

1. Download both the catalog.xml and catalogempty.htm files from the

Chapter 10 page of the XML in 60 Minutes a Day Web site into the

C:\WWW\SpaceGems directory

Trang 5

2. Open the catalogempty.htm file using HTML-Kit You should see apartial HTML file solution with comments inside it, similar to thiscode:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

<! Data island start >

<! Data island end >

<! Navigation buttons start >

<! Navigation buttons end >

</body>

</html>

3. Rename the file catalog.htm and save it

4. Open the catalog.xml file using HTML-Kit This is the data sourcefor this exercise Review the document but do not make any changes

to it When you are familiar with the file’s structure and contents,you can close it

5. Open the catalog.htm file again and create a reference to an externaldata island inside it by adding the appropriate code between the dataisland comment lines When done, the lines should look like this:

<! Insert the XML data island >

<xml id=”data” src=”catalog.xml”></xml>

<! Insert the HTML table code after this line >

6. Note that the value specified for the id attribute—the data source

Trang 6

<span style=”background: white;

width:150; border: inset;

<span style=”background: white;

width:150; border: inset;

<span style=”background: white;

width:150; border: inset;

<span style=”background: white;

width:150; border: inset;

<span style=”background: white;

width:150; border: inset;

Trang 7

8. Anytime you want to see the progress, click the Preview tab withinHTML-Kit Feel free to change the HTML look and feel if you thinkthis file is too ugly for words.

9. Add the following JavaScript code to the catalog.htm Web pagebetween the appropriate comment lines, as indicated:

if(data.recordset.absoluteposition>1) data.recordset.movePrevious();

} function next(){

if(data.recordset.absoluteposition <

data.recordset.recordcount) data.recordset.moveNext();

} function last(){

11. Create the navigation buttons that will invoke the functions definedpreviously Add the following code to the catalog.htm file betweenthe appropriate comment lines:

<! Navigation buttons start >

Trang 8

12. View the file inside HTML-Kit Preview, and save the file.

13. Using Internet Explorer, enter http://localhost/SpaceGems/

catalog.htm into the locator bar If successful, the display shouldresemble Figure 10.16 Check the functionality by clicking the navigation buttons

14. For optional practice, you can add another link to the index.htmlpage, one that will give you instant access to this page The code is asfollows Just follow the procedure indicated in the earlier exercises

<a href=”catalog.htm”>Space Gems Catalog</a>

15. When you are done, don’t forget to test the new link

Figure 10.16 Space Gems Catalog including JavaScript navigation functions.

Summary

Several concepts discussed in this chapter serve us well with respect to nativeXML data and to discussions of other database technologies, especially whenthey are applied in the Internet world:

Trang 9

■■ More and more individuals and organizations are adopting XML nologies and standards, and native XML databases are expected to play

tech-a ltech-arger role in the future However, they tech-are not expected to unsetech-atrelational database technology The challenge will be to increase theirinterchangeability

■■ Data binding is the process of mapping and synchronizing data in adata source to designated (usually local) data placeholders In thischapter, data consumer elements, also called bindable elements, are theplaceholders Data binding also involves moving and synchronizingdata from a remote server to a local system and manipulating it on thelocal system

■■ The advantages to data binding are reduced network traffic, lighterloading on servers, and more efficient use of local resources

■■ Data consumer elements bind two types of data: single-valued and tabular Inserting more than one value at once is called data set binding

■■ HTML extended attributes, such as datasrc and datafld, allow us

to point to data sources and to the data fields within those sources,respectively

■■ XML data is stored in internal or external data islands Internal dataislands are located within the Web page documents that display andmanipulate the data External data islands are located in separate documents that are referred to by the Web page documents

■■ XML data retrieval and synchronization are performed by the XMLdata source object plus the data binding agent or the table repetitionagent XML DSO activation is easier and more automatic since therelease of Internet Explorer 5

■■ The DSO is activated by the data binding agent or the table repetitionagent The DSO retrieves data and assembles it in recordsets in the localbrowser

■■ Basic XML recordset navigation can be facilitated quite easily withJavaScript coding in the Web page documents themselves

Trang 10

Review Questions

1. Which of the following is not an aspect of data binding?

a. Mapping and synchronizing data

b. Interchangeability with relational databases

c. Transmitting data from sources to data placeholders

d. Local data manipulation

e. None of the above

2. Which of the following are data bindable elements? (There may be more than one correct answer.)

a. <div>

b. <table>

c. <span>

d. <td>

e. All of the above

3. True or false? The <div> element is a grouping element, but the <span> element isonly an inline element

4. True or false? Single valued elements can be used to build tablelike structures

5. To display data from a data source without worrying about the format of the data,which of the following attributes would you use?

a. datasrc=”$text”

b. datafld=”$text”

c. datasrc=”$table”

d. datafld=”table”

e. None of the above

6. Which of the following attributes points to an external XML data island?

Trang 11

7. The standard syntax for specifying data located below the second nesting level bles which of the following?

e. None of the above

9. True or false? The DSO searches a Web page document for bindable elements, thenactivates the data binding agent or the table repetition agent

10. Which of the following atttributes could tie navigation buttons to JavaScript functions?

Trang 12

Answers to Review Questions

1 b The interchangeability of native XML data and relational databases is an objective of

developers and vendors of both technologies But interchangeability is not an aspect

of XML data binding

2 a., b., and c The <td> element can only be used if a <div> element is nested within it.

3. False In fact, the statement is a little nonsensical Both the <div> and <span> elementsare grouping elements However, <div> is block level while <span> is inline level

4. True In fact, two examples are provided in the text, in the section titled The <table>

Element

5. b This is discussed in the Single-Valued Elements Avoid Overrestrictive Data section.

6. c This is discussed in the External Data Island section.

7 a Remember, the first term is the name affiliated with the second level The delimiter

is a period

8 a The <xml /> element has to be declared an empty element type, and the two

relevant attributes are id and src

9. False Actually, the reverse is true: The data binding and table repetition agents search

a Web page document for bindable elements; if they find any, they activate the priate DSO

appro-10. d This is discussed in the Navigating Recordsets section.

Trang 14

Even though it has only been about 10 years, the World Wide Web seems tohave moved worlds away from its initial “text-only” days During the pastdecade, graphics have become so important that—let’s face it—a Web sitewithout graphics isn’t even considered a proper Web site Research demandsgraphics, e-commerce demands graphics, and those who just want to have funreally demand graphics In light of these ever-increasing demands, it is impera-tive to deliver graphic images (diagrams, still pictures, movies) while simulta-neously optimizing the consumption of system and network resources

In this chapter, we introduce the Vector Markup Language (VML), presentlythe most widespread of the XML-related graphic languages We start by review-ing some basic graphic technology concepts, then provide a quick definitionand background for VML itself Finally, we show you how to create VML doc-uments and figures By the end of the chapter, you will be able to create yourown VML objects, manipulate them, and display them in your browser

A word of caution, though: As a graphics standard, Scalable Vector Graphics(SVG) is gaining acceptance in the IT world Within the next few years, it mayeclipse VML

VML

C H A P T E R

11

Trang 15

Basic Digital Imaging Technologies

Two basic digital imaging technologies exist: those using bitmap graphics andthose using vector graphics Although VML involves vector graphics, each isdiscussed in turn

Bitmap Graphics

A bitmap graphic file (also known as a raster graphic file) is one in which each

bit of data in the file corresponds to a specific location on a raster—which is theviewing area of a terminal screen—or to a specific ink dot on a printed page.Actually, the converse of that statement may be easier to understand: The data

value for each picture element (usually called a pixel) is stored in a data file.

Pixels are easily seen on terminal screens (and television screens) by looking atthe screen through a magnifying glass They are similar in nature to the com-binations of black and white or colored ink dots that are still used to createnewspaper and magazine photographs The resolution (Windows calls it thescreen image) that you specify for your terminal is measured in pixels Forexample, 800 by 600 (also indicated by 800x600) means that there are 800columns and 600 rows of pixels in your viewing area The higher the numbers,the sharper the image that can be displayed However, if you have highernumbers in your resolution setting, you will generally need larger data files tostore the image data

A bitmap is also characterized by its color density, which is the number ofdata bits required to display each pixel The bits per pixel may vary from four

to 32, depending on the number of shades of gray, or the combination of red,green, and blue colors per pixel For example:

■■ If we want 16 colors, each pixel requires four bits of data

■■ If we want 256 colors, each pixel requires eight bits

■■ If we want 65,536 colors (high color), each pixel requires 16 bits

■■ If we want 16.78 million colors (true color), each pixel requires 24 bits

We can readily see that if we want a higher color density in an image, weneed a larger data file

Classroom Q & AQ: What’s with all those bitmap formats: GIFs, TIFFs, JPEGs, and theothers? What’s the difference?

A: Bitmap files do indeed occur in various formats, depending on thefeatures of the various algorithms used to compress the datawithin them If the files weren’t compressed, they would take up

Trang 16

much more storage space and take much longer to transmit anddisplay These formats are referred to by their acronyms (BMP,TIFF, GIF, PNG, or JPEG) and are also reflected in the extensionsadded to the respective data filenames The various formats allowgraphic files to be exchanged between several different platformsand applications

The header of a bitmap file specifies the file format, the dimensions of thedisplay in pixels, and information about color density Following the header arethe data bytes that create the image Output devices, such as printers and mon-itors, contain rasterizers, which are combinations of hardware and softwarethat translate all graphic objects into bitmaps Thus, with some output devices,all graphic objects (including vector graphic objects, which are discussed in thenext section) must be translated into bitmaps before being produced

The advantages to bitmap graphics include the following:

■■ Because the composition of each individual display pixel or printed dot

is controlled, bitmapped images do not need on-time calculation, whichlessens their consumption of CPU cycles

■■ Bitmaps are found just about everywhere on the Web and on privatenetworks

■■ Bitmaps allow us to enhance image details; we can literally modify eachpixel in an image using applications that are commonly called paintprograms or photo suites

But bitmap graphics have several disadvantages, too Among them:

■■ They may require a larger amount of RAM on motherboards, videoadapter cards, or within printers

■■ Bitmap images still require fast processors, since video terminals may require a wholesale image change (also called a refresh) between

50 and 200 times per second, depending on monitor characteristics

■■ The generally larger file sizes cause them to download slowly (especially frustrating when subject to slow Web connections)

■■ The files are usually stored externally with respect to the rest of the Webpage or other containing documents, which causes processors to workharder, makes the images more difficult to distribute, and causes extrasystem administration issues

■■ They do not provide real overall flexibility: Once the image has beencreated, significant changes cannot be easily made Even minor changescannot be made without using the appropriate paint or photo software(which likely includes software to uncompress and then recompress the

Trang 17

files) on a system that must meet certain minimum requirements Thus,you cannot access a bitmap, make quick (and, especially, significant)changes, and redraw it quickly

■■ Bitmap graphic images become jagged looking beyond a certain fication level

magni-Vector Graphics

Vector graphic images are objects created by drawing a series of lines,

poly-gons, and text, while providing only the starting positions and directions for

each line Vector graphic images are also called object-oriented graphics, but

they are not related to object-oriented programming

The drawing activity is actually the activation of mathematical expressionsand descriptions in an application, which, in turn, will use attributes provided

in the respective Web document to create representations of the vector images.Vector graphics always use one or more algorithms in real time to create ashape and then draw that image on the screen or send it to a printer Vectorgraphic files create bitstreams that describe their images as display lists thatcontain a mathematical description of every object in a shape (imagine a jewelbeing composed of triangles, octagons, and other individual objects groupedtogether), including their respective locations and dimensions, as well as otherattributes like fill colors, line stroke widths, and layers

Vector graphics are widely used in word processing, graphics editing, lishing, and presentation applications Almost all sophisticated graphics sys-tems, including computer-aided design and drafting (CADD or CAD) systemsand animation software, use vector graphics Applications used to create andmanipulate vector graphics are generally called drawing programs (as opposed

pub-to the paint programs used pub-to manipulate bitmap graphics) In everyday wordprocessing, fonts are often created using vectors These are called vector fonts,scalable fonts, object-oriented fonts, and outline fonts Some vector graphic-enabled output devices contain built-in interpreters that execute the instruc-tions (as opposed to rasterizing into bitmaps)

Vector graphics have several advantages:

■■ Vector graphics files use smaller amounts of memory to represent arespective object no matter what the intended actual size If the graphicsfiles are altered to create bigger or smaller images, almost no differenceoccurs in the size of their already smaller definition files, thus savingRAM and hard disk drive storage

■■ The smaller files also transmit (download) faster

Trang 18

■■ Vector graphics are more scalable Their representations can potentially

be output on any device, with any resolution, and at any size, with noloss of clarity and no distortion In fact, they look better when dis-played at higher resolutions and at higher magnifications By contrast,bitmapped images become jagged at higher magnification and look nobetter on higher-resolution devices than on lower-resolution devices

■■ Overlapping shapes can be manipulated independently without usingdifferent layers for each

■■ Once vector graphic files are created, the objects within them can

be selected, resized, moved, and reordered at any time; significantchanges can be made, more quickly than the “pixel detailing” of bitmap manipulation

■■ Vector graphic files are searchable for data and attributes

■■ Users can interact easily with the created image files using a simplecomputer system and text editor Vector files are actually text files

The disadvantages of vector graphics are as follows:

■■ As vector graphics become more sophisticated (possibly containingscores, hundreds, or even thousands of mathematical expressions thatdefine many finer details), more powerful processors may be needed tohandle them It may take significant time to redraw or output (that is,recalculate, pass the information to a rasterizer, store the data in RAM,and quickly transfer and refresh it to a screen) all the objects, not onlyall at once, but at perhaps hundreds of times a second as a monitorscreen refreshes This may result in flicker as you move an image to anew location on a page

■■ The very fine image details might be better handled by bitmaps

As a workaround for these bottlenecks and to save processing time, someprogrammers develop software that includes strategically placed bitmappedfonts or other images in otherwise vector graphic files They still allow the use

of vector fonts and images to produce fine results in hard copy

VML Development

VML was designed to help developers address the problems and tages of bitmap technology and to provide a textual method for prescribingvector graphics Those prescriptions can be easily transferred to a wide variety

disadvan-of authoring tools, from the simple to the sophisticated, by simple paste methods Further, VML is written so that it can be integrated into exist-ing HTML 4.0 Web-related documents

Trang 19

cut-and-The initial VML draft specification was authored jointly by Autodesk Inc.,Hewlett-Packard Company, Macromedia Inc., Visio Corporation, and MicrosoftCorporation, and it was submitted to the W3C in May 1998 The VML specifi-cation never attained W3C Recommendation status, despite the support ofMicrosoft and other developers This support included the incorporation ofVML graphic-rendering functionality into recent versions (since Version 5.0)

of Microsoft’s Internet Explorer browser The VML specification documentsurvives as a W3C Note (As mentioned in Chapter 6, a W3C Note is a dated,public record of an idea, comment, or document Publication as a Note doesnot represent any commitment by the W3C to pursue work related to it Neither does its Note status indicate any endorsement of its content, nor anypresent or future allocation of resources to the issues addressed by it.)

Thus, no further VML development is likely to take place In fact, both theVML Note and the (rival) Precision Graphics Markup Language Note (alsosubmitted in 1998) were overtaken and passed by the development of the Scal-able Vector Graphics specification, which became a W3C Recommendation inmid-2001 We discuss these documents in the last sections of this chapter

What Is VML? A Definition

The W3C (at www.w3.org/TR/NOTE-VML) describes VML as follows: “VML

is an application of the Extensible Markup Language (XML) 1.0, which defines

a format for the encoding of vector information together with additionalmarkup to describe how that information may be displayed and edited.”VML is fully compliant with other W3C standards such as Cascading StyleSheets, HTML, XHTML, and others For example, all top-level VML elementssupport the <style> element and its related attributes, in the same manner thatall HTML elements support it Further, since VML also supports CSS, shapescan be styled and positioned as required by a Web document developer True to its vector graphics heritage, VML uses mathematical descriptions toprescribe its shapes VML’s vector graphics definitions can be included withinXHTML-/HTML-compliant documents (integrated with the Web page coding).Unlike bitmaps, VML definitions are not relegated to external files True to itsMicrosoft heritage, VML also contains a few MS Office-related features that allow

it to cooperate with VML generated by Microsoft 2000 and XP technologies Images can be generated using nothing but VML However, bitmap data isstill considered important to VML and can be combined with vector data byincluding appropriate references Furthermore, VML provides (admittedlylimited) transformation attributes (such as chromakey, gamma, picture, andblack level adjustments) that can be applied to the bitmap data from within theVML/Web document

Trang 20

Some of VML’s advantages stem from its vector graphics heritage; somefrom its Microsoft Internet Explorer affiliation:

■■ VML’s vector graphic files are generally smaller, so they transmit fasterthan bitmap images

■■ VML documents are easily and quickly created, updated, and lished to servers Editing activities can be done using text editors orother office environment applications The files can be republisheddirectly and quickly after that

pub-■■ VML is both open and standards-based It is compliant with other W3C standards such as HTML, XHTML, and others, including, asmentioned previously, Cascading Style Sheets

■■ Because it is a text-based encoding system, developers are able tosearch, cut, and paste vector graphics from one document to another,and scale VML graphics to interact with other page elements andobjects When a page is displayed in a browser window, the source code can also be viewed

■■ VML has become the most widespread graphics-related XML tion (although the Scalable Vector Graphics Recommendation is closingthe gap) and comes incorporated with recent versions of Microsoft’sInternet Explorer browser Thus, it is accessible to a wide audience andrequires no additional downloads or plug-ins to be functional

applica-■■ VML does not always require the implementation of a rasterizer

Existing operating system facilities can be used, such as those found inthe Win32 Graphical Device Interface (GDI, the Windows standard forrepresenting graphical objects and transmitting them to output devices)

or Macintosh QuickDraw (the underlying graphics display system forApple Macintosh computers)

■■ Although images can be generated using nothing but VML, bitmap datacan also be combined with vector graphics data VML also providessome bitmap transformation attributes

These advantages all contribute to faster Web site design and have allowedVML to contribute to geographic information system technologies, whereVML’s map-making and drawing strengths can be quickly and easily employedalongside XML-related spatial databases

Creating VML Documents

Now that we know something about VML’s background and basic vectorgraphic technology, it’s time to introduce its structure and other features

Trang 21

Because VML is an application of XML, if it is used in an XML/XHTML ronment, its syntax must be strictly adhered to If VML is used in an HTMLenvironment, however, not all XML-like features need be included

envi-Logical Structure: A Prolog and an <html> Element

VML document structures are very similar to XHTML/HTML documents AVML document consists of two main parts: a prolog and an <html> element The prolog resembles other XHTML-related documents It consists of anXML declaration and a DOCTYPE declaration indicating the DTD variant.However, a prolog is not necessary when VML is used with HTML

The <html> element consists of the <head> element and the <body> ment In a VML/XHTML document, the <head> element contains a <title>element followed by a <style> element The <style> element also contains abehavior declaration, which is discussed later

ele-Namespace Declarations

For VML to render properly, we must pay attention to the namespace tions Two namespace declarations are necessary: a VML namespace and adefault namespace for the HTML or XHTML tags Both declarations mustappear in the <html> element’s start tag

declara-Here is the VML namespace declaration that should appear in the <html>start tag:

<html xmlns:v=”urn:schemas-microsoft-com:vml”>

When we are declaring a VML namespace, convention prescribes the prefix

v: Later in the document, needless to say, the v: prefix precedes each

VML-related element tag

If we omit the VML declaration, the VML figures will not be displayed If you ever have trouble producing VML output, start debugging by looking for this declaration in your documents.

The default namespace is inserted next, in the same <html> element starttag If our document is XHTML-compliant, the default declaration must reflectthat In that case, add the following as the default namespace declaration to the

<html> start tag:

xmlns=”http://www.w3.org/1999/xhtml”>

Trang 22

If our document is not Xcompliant (that is, if it is only compliant), then we have to add the following default namespace declaration

HTML-to the <html> start tag, instead of the previous declaration:

xmlns=”http://www.w3.org/TR/REC-html40”>

The code used tells Internet Explorer that all tags without prefixes are part

of the XHTML or HTML namespaces, respectively

Because of VML’s Microsoft heritage, it is supported by Microsoft Office2000/XP applications: Microsoft Word, PowerPoint, and Excel We can usethose applications to draw VML objects, but you must add a third namespacedeclaration to the <html> start tag, since those applications will add the prefixo: to their VML elements The third declaration follows:

Since they are complete in themselves, we can declare behaviors at thebeginning of an XHTML/HTML document and then apply (or “call”) them toany element in our document Thus, behaviors provide the ability to reuseblocks of code and to keep our content separated from that actual code

To activate IE’s VML behavior, insert the following code into the <style> element within the <head> element:

Trang 23

Once again, because VML is supported in several recent Microsoft Officeapplications, if we create VML objects with those programs, we must add thisbehavior declaration to the <style> element:

o\:* {behavior:url(#default#VML);}

Later, you will learn how to create primitive graphic objects (objects created

by setting a path for a virtual pen to traverse) When adding such objects to

a VML document, we must add a shape behavior declaration to the <style>element:

.shape {behavior:url(#default#VML);}

The shape referred to here is like an object-oriented programming class

name In embedded-style behaviors like this, the class name is used as a tor and begins with the period (.) This causes every element assigned the class

selec-name of shape to be rendered according to the specifications in this IE behavior.

VML Elements in the <body> Element

The VML elements that we use to create shapes will appear within the <body>element of the XHTML/HTML Web page document Those elements are cate-gorized according to their function within a VML-related hierarchy of cate-gories Some elements are members of more than one category The maincategories, along with examples from each, are listed in Table 11.1 (Several ofthe elements listed in Table 11.1 are discussed in this chapter; for details onthese and other elements, please refer to the W3C VML Note at www.w3.org/TR/NOTE-VML.)

VML applies to each element a default template consisting of the full set ofattributes that may apply to that particular element In the following section,for example, we discuss the <shape> element and Table 11.2 lists the defaultVML template for that element However, when we specify a particular ele-ment type, we can override the default values for any of its attributes by spec-ifying the attribute name and a new value

Table 11.1 VML Element Categories

<strokeweight>, <handles>, <image>, <imagedata>

<oval>, <polyline>, <curve>, <arc>

Trang 24

The <shape> Element

Creating a <shape> element is the first step toward defining our own vectorgraphic figure But <shape> really only defines the containing box for the

actual figure we want to create When this block-level box is created, we use the

<shape> element’s coordsize and coordorigin attributes to define a local dinate system for any subelement figures that may be created within the box.Thus, any subsequent positioning information specified for subelement fig-ures is expressed in terms of the box’s local coordinate space As a result, posi-tion attributes like left, top, width, height, and others are not expressed incommonly recognized measures like inches, millimeters, or the like; they areexpressed as coordinate divisions, as you have defined them, within the box

coor-To clarify, the coordsize attribute defines how many divisions exist along thebase of the containing box, across its width The coordorigin attribute specifiesthe coordinates of the top left corner of the containing box This strategyallows the vectors defining a figure inside the block-level box to be specifiedwith respect to its local coordinate system Later, if the dimensions of the con-taining box are changed, the outline of the figure will be automatically scaled

to the new dimensions

To create a figure inside the block-level box, specify a path within <shape>.The path may take the form of a path attribute or a <path> element Both arediscussed in the next section

Table 11.2 lists the attributes, complete with their default values, that make

up the <shape> element’s default VML template Notice that some values usequotes, while others do not Those with quotes are standalone attributes; thosewithout, appear within a style=” ” attribute To override any of <shape>’sdefault attribute values, insert the attribute name and specify a new value inthe <shape> element’s start tag

Table 11.2 Default Template for the <shape> Element

Trang 25

<shape fillcolor=”gray”

style=”position:relative;top:1;left:1;width:400;height:300” path=”m 1,1 l 1,300, 400,300, 400,1 x e”>

</shape>

From the example, you can see that we must define, at a minimum, a

<shape>’s position, top, left, width, height, and path attributes The fillcolorattribute was included because the path is an attribute If instead we had used

a <path> element, the fill color would have been specified within the <path>element’s start tag

Although the most basic of VML’s graphic elements, <shape> is not used asfrequently as we would expect Most developers prefer to use predefinedshapes like <rect>, <oval>, <line>, and others These are discussed later, in the

section titled VML’s Predefined Shapes.

Creating Graphic Objects Using the path Attribute or <path> Element

To define what are called primitive graphic objects (which we refer to as shapes

or figures) within the <shape> element, we either use a nested <path> element

within the <shape> element, or specify a path attribute within the start tag ofthe <shape> element

Trang 26

As stated earlier, if we are going to add primitive graphic objects to our VML documents using a path attribute or a <path> element, then we have

to add a shape behavior declaration to the <style> element For details,

refer back to the Behavior Declarations section.

The path Attribute

Within the <shape> element, we can specify the figure we wish to draw byusing the attribute named path and specifying, as a value for that attribute, anexpression that includes a string of x,y coordinates plus one or more virtualpen commands The path attribute thus defines the outline of a shape by pre-scribing a path consisting of a sequence of straight lines, Bézier curves, or both(technically, these represent a list of vector-based drawing operations)

Classroom Q & AQ: Sorry to interrupt again, but what kind of curves?

A: Bézier curves (pronounced “bez-ee-ay” and named after the Frenchmathematician Pierre Bézier) are curved lines defined by at leastthree specified points Mathematical formulas are used to plot therest of the points (see the c command in Table 11.3)

Once prescribed, the outline of the shape may then be stroked, filled, orotherwise modified according to the values you specify for other attributes.The basic syntax for a path attribute within a shape element is as follows:

<shape path=”expression” >

Nineteen pen commands are available: m, l (the letter “ell”), c, x, e, t, r, v, nf,

ns, ae, al, ar, at, wa, wr, qx, qy, and qb The most commonly used commandsare described briefly in Table 11.3

Table 11.3 Path Attribute Pen Commands

coordinate.

given (x,y) coordinate, which becomes the new current point To form a polyline, specify

a number of coordinate pairs.

(continued)

Trang 27

Table 11.3 (continued)

to the coordinate given by the final two parameters (the control points are given by the first four parameters following the c).

straight line from the current point to the original moveto point.

coordinates specified.

given relative coordinate

using the given coordinate relative.

Here is an example that draws a simple diamond shape:

the style-position attribute, the given coordinates are in relative coordinate space

(the space is prescribed by the coordorigin and coordsize attributes); the truesize will be determined by the width and height specifications The pointsspecified are just x,y values in the units of the coordsize attribute of the shapeelement

Spaces, as well as commas, may be used as delimiters when specifying point coordinates For example, path=”m 0 100 l 100 200 200 100 100 0 x e” is equivalent to path=”m 0,100 l 100,200, 200,100, 100,0 x e.”

Trang 28

Furthermore, if we are using zeros in our path description while using commas as delimiters, we should consider leaving the zeros out Thus, path=”m 0,100 l 100,200,200,100,100,0 x e” is equivalent to path=”m ,100

l 100,200,200,100,100, x e.”

The <path> Element

As an alternative to the path attribute, a <path> element can be nested within

a <shape> element—or even within a <shapetype> element, which we discuss

later in a section titled The <shapetype> Element for Frequently Used Custom ures, to prescribe an outline for a figure.

Fig-Within the <path> element (notice that it is a declared empty element),

pre-scribe your figure by inserting the attribute named v and specifying as values

for that attribute an expression that includes a string of x,y coordinates plusone or more virtual pen commands Thus, the procedure is similar to that ofthe path attribute within <shape>

Although the activation syntax differs, ultimately the pen commands are thesame as those listed for the path attribute: m, l (the letter “ell”), c, x, e, t, r, v, nf,

ns, ae, al, ar, at, wa, wr, qx, qy, and qb The most common of those commandsare described in Table 11.3

Using the simple diamond example again, the <shape> syntax, includingthe nested <path> element with its v attribute, is as follows:

<shape strokecolor=”black” fillcolor=”gray” coordorigin=”0 0”

Classroom Q & AQ: What if a <shape> element contains both a path attribute and a

<path> element with a v attribute, and the paths contradict?Which will prevail?

A: If that happens, the specifications within the <path> element willprevail over any values specified for the path attribute in the

<shape> element

Trang 29

Q: So, which should we use? A <shape> element containing a pathattribute? Or a <path> element?

A: If we are not prescribing a complex shape, we are more likely toconserve resources by using the path attribute strategy Otherwise,for more sophisticated shapes, it would be better to use the

<path> element and its attributes

The same use of spaces as delimiters and the omission of zeros when commas are used as delimiters also apply to the use of the <path> element

Table 11.4 VML’s Predefined Shapes

<arc style=’width:200pt;height:200pt’

startangle=”0”

endangle=”-90” coordorigin=”200 500” strokecolor=”black” strokeweight=”2pt”/>

<curve from=”300pt,350pt”

control1=”400pt,350pt”

control2=”600pt,500pt” to=”670pt,600pt” strokecolor=”black” strokeweight=”2pt”/>

Trang 30

Table 11.4 (continued)

rectangle is created that is the same size as the image.

Example:

<image style=”width:300pt;height:200pt”

coordorigin=”300pt, 550pt”

src=”c:\SpaceGems\images\diamond.gif” />

<line from=”700pt,100pt” to=”950pt,100pt”

strokecolor=”black” strokeweight=”4pt”>

Vertical line example:

<line from=”150pt,50pt” to=”150pt,250pt”

strokecolor=”black” strokeweight=”4pt”>

height property values) Oval example:

another “head-to-toe.” Example:

<polyline points=”550pt,200pt,650pt,200pt,750pt, 300pt,850pt, 300pt,950pt,400pt,950pt, 500pt”

Trang 31

Table 11.4 (continued)

addition of the arcsize attribute, which accepts values between 0 (square corners) and 1.0 (semicircular).

Example:

<roundrect style=’width:250pt;height:100pt’ arcsize=”0.25”

fillcolor=”white” strokecolor=”black” strokeweight=”2pt”/>

Predefined shapes provide a method for quickly drawing frequently usedfigures The shapes are easily edited, since they have a more natural-soundingsyntax For example, instead of drawing a rectangle using a combination of the

<shape> and <path> elements, we only have to use the <rect> element.Table 11.5 lists the default templates for VML’s predefined shapes Noticethat both common and specific attributes are listed for each element type

Figure 11.1 Predefined shapes in VML

700 600 500 400 300 200 100

Trang 34

The <shapetype> Element for Frequently Used Custom Figures

Although predefined shapes are very handy for defining commonly usedshapes and are convenient alternatives to using <shape> elements with pathattributes or nested <path> elements, there are times when we want to create

a custom-designed figure and use it repeatedly At these times, when fined shape elements can’t help us, the <shapetype> element can be used

prede-The <shapetype> element allows us to predefine a customized figure thatcan be used repeatedly later Thus, we can create a prototype shape, provide itwith a unique identifier, and refer to it when needed The following example

of a customized <shapetype> element defines a simple envelope shape:

<shapetype id=”envelope” coordsize=”10 10” >

Please note that the <shapetype> element by itself does not cause the figure

to be inserted It only contains the specifications for the figure Only when weinsert the subsequent and corresponding <shape> elements will the figure bedrawn Please note, too, that in the sample <shape> element syntax, the fill-color and strokecolor attributes were specified as white and black, respec-tively Specifying different values in the <shape> element will override thevalues originally specified in the <shapetype> element We can also alter otheraspects of the figure by setting or changing other property attributes withinthe <shape> element

Trang 35

If a designer intends to control any or all three aspects, the VML styleattribute will play a major role This section discusses all three aspects

Static Positioning

VML’s default position style is static positioning, which instructs the parser toplace a figure at the current point in the text flow and to ignore any top or leftsettings that might appear in the style attribute

As a simple example, say that we want to place a blue circle immediatelyafter the text “This is our blue circle” but before the word “See?”

<body>

This is our blue circle.

<v:oval style=’width:100pt;height:100pt’ fillcolor=”gray”

Absolute Positioning

If we insert the position property into the style attribute of a figure’s start tagand then set the value of the position property to absolute, the applicationlooks for subsequent properties as a prescription for where to place the fig-ure’s containing box The subsequent properties specify the distance from thetop left corner (the base point) of its parent element (presumably, another posi-tioned element that is intended to contain the figure)

To clarify, let’s look at an example Note that in the static positioning ple, the blue circle is contained within the <body> element (that is, within theentire Web page) Its base point, then, is the top left corner of the Web page.Now we alter the code with the position:absolute property so that the circle’sblock-level display box is exactly 20 points to the right of and 10 points downfrom the top left corner of the Web page:

Trang 36

two statements That’s why we changed the first statement to “There is ourblue circle” from “Here is our blue circle.”

Relative Positioning

Relative positioning allows us to place (that is, offset) a figure’s block-level play box in a precise position relative to the current (or base) point in the text

dis-flow Relative positioning is activated by the use of the value relative for the

position property within the style attribute The offset distance is prescribed

by the values specified for the top and left properties in the style attribute Thecontaining box will once again, as in VML’s default static positioning, take upspace in the text flow

Let’s create another blue circle example that places the blue circle 100 points

to the left and 25 points lower than the current point in the text flow:

Overlapping Figures: The z-index

Occasionally, figures overlap, whether by accident or by design VML’s defaultbehavior is to display the most recently prescribed figure on top of those pre-scribed earlier However, by specifying z-index properties in the style attribute

of the respective figures’ start tags, a designer can create a layering hierarchy.The value of the z-index specification can be a negative integer (for example,–2), zero, or a positive integer (like +3) The figure with the most positive z-index value will be displayed on top of figures with less positive z-index val-ues Meanwhile, if two or more figures have the same z-index value, the layer-ing reverts to default behavior Z-indexes can also be applied to <shapetype>and <group> elements

In the following example of respective z-indexes, our blue circle with grayfill will be displayed on top of another figure, a green rectangle:

Ngày đăng: 14/08/2014, 12:20