[HTML5-SVG] the new field of JavaScript-dynamic image processing (SVG)

Source: Internet
Author: User
Tags cdata

Background

When JavaScript was invented by Netscape, it was used to perform fine-grained tasks, such as validation.FormComputing date, prompting users; with the rapid development of the Web, this lightweight and flexible language is entrusted with more and more tasks, dynamic modification of page content, consistent processing of events, you can even interact with the server without any need. However, compared with traditional Client programming, JavaScript operation objects are restricted within the DOM model and cannot be programmed in graphics. So for a long time, when designing webpages, we are just building blocks, and these blocks have only one shape-rectangle. These rectangular blocks are the "Box Model" applied to HTML elements ). Each box has borders, edges, and pads ). We can only control the size and limited style of these boxes. The collection of these squares is sufficient for building a traditional document page. However, the popularity of the Web has made the web page undertake more tasks than transmitting text information. If there is popularity, there will be demand, and there will be innovation wherever there is. The Art Design of Web pages has made static pages look better than traditional clients.Program. Creating more interactive user interfaces makes it very attractive to create and modify images on pages. As a result, the two technologies came into being, allowing JavaScript Functions to be extended to the graphic field.

Two Digital Image Solutions

Before introducing these two technologies, let's take a look at the digitization of images. There are two solutions to store images as data. One is a bitmap, also known as a grating. That is to say, the image is a collection of dense arranged points on the plane from the perspective of natural optics. The light emitted by each vertex has an independent frequency and intensity, which is reflected in the Visual Color and brightness. This information has different encoding schemes. The most common on the internet is RGB. As needed, the encoded information can have different bit values-bit depth. The higher the number of digits, the clearer the color, the higher the contrast, and the larger the occupied space. Another item that determines the fineness of a bitmap is the number of vertices. A bitmap file is a collection of all the data that makes up its points. Its size is equal to the number of points multiplied by the bit depth. The bitmap format is a huge family, including common JPEG/jpg, GIF, Tiff, PNG, and BMP formats.

The second solution is vector graph. It looks at the image from an abstract perspective and records the presentation mode instead of the original data of each point. It regards an image as a combination of various "objects", uses a curve to record the outline of an object, and uses a certain color pattern to describe the internal pattern of the object (such as gradient to describe gradient ). For example, a shadow is regarded as a combination of various scenes in different figures and backgrounds. This more advanced perspective is exactly the reflection of human beings looking at the world in consciousness. Vector image formats include CGM, SVG, AI (Adobe Illustrator), CDR (CorelDraw), PDF, SwF, and VML.

A simple ry in a vector graph can be determined only by a few feature values. For example, a triangle only needs to determine the coordinates of three vertices. The Circle only needs to determine the coordinates and radius of the center. To describe the known curves of the function, you only need a few parameters. Such as sine curves and various nuts. If you use bitmap to record these geometric patterns, You need to include the data of each pixel that makes up the line. In addition to space saving, vector graphs are also perfectly scalable. Because the characteristics of the image are recorded, when the size of the image changes randomly, it only performs similar transformations without blurring or distortion. On the contrary, when an image larger than the original size is enlarged, there is a gap between each pixel.AlgorithmFill in, and the phenomenon such as fuzzy sawtooth will also appear, not as accurate as the vector graph. Therefore, vector graphs are suitable for recording simple images such as symbols and icons. While bitmap is suitable for images without obvious rules and with rich and delicate colors.

Two technologies

Now let's go back to the drawing on the web. There is one technology corresponding to the two digital image solutions. In the chronological order of their generation. This articleArticle.

SVG

The first technique comes from the XML family, which is called SVG (scalabe vetor graphics)-a scalable vector graph. As a common data format, XML has been expressing all the aspirations of what can be expressed since its birth, not only accepting new information, it also receives data stored in other forms in history. Its ambition to expand its map is no less than that of any ambitious monarch.

XML is suitable for describing structured data, so you may have guessed it. As shown in its name, the SVG chooses a vector image. In fact, SVG is far from the first way to describe images in XML format, or even the first way to combine XML and vector images on the web. In July 1998, Macromedia and Microsoft submitted VML (Vector Markup Language) to W3C, Adobe and Sun submitted pgml (precision graphics Markup Language ), these two types are based on the XML vector chart specification. Subsequently, other companies that do not want the Vector Picture standards on the Internet to be monopolized by these giants set up a specialized group SVG working group within W3C. After drawing on the first two proposals, the SVG specification was proposed and subsequently accepted as the W3C recommendation equivalent to the standard (W3C recommendation ). The main development history of SVG so far is as follows:

2001-9svg 1.0 is recommended by W3C.

2003-1svg 1.1 is recommended by W3C. And evolved the details of different levels of SVG Tiny, SVG basic and SVG full.

SVG 1.2 has been in the W3C working draft State for a few years and is determined to be replaced by SVG 2.0.

SVG 2.0 will completely rewrite SVG 1.2 to add more new features such as CSS and HTML5.

The first simple example

The following is a simple definition of a vector graph. Detailed descriptions of various elements and attributes in SVG can be found in special references. This article describes some important elements and attributes in the example.

Listing 1. An SVG file

<? XML version = "1.0" standalone = "no"?> <! Doctype SVG public "-// W3C // dtd svg 1.1 // en" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <SVG xmlns = "http://www.w3.org/2000/svg" version = "1.1" width = "100%" Height = "100%"> <circle Cx = "100" Cy = "100" r = "40" fill = "red"/> </SVG>

 

The XML command of the first line defines the version and indicates that this file is referenced to other files. The second line is the document type definition, which specifies which SVG elements are valid in this XML. The http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd referenced here is exactly why the standalone attribute in the first line is no. The third line begins with the real definition of SVG. The circle element specifies to draw a circle. The CX, Cy, and r attributes specify the abscissa, ordinate, and radius of the center respectively. The fill attribute specifies the area inside the circle in red.

Easy to draw

Paste the text into any text editor and save the file as an SVG file, such as Sun. SVG. You have drawn a picture-a red sun. But it is not that easy to read. You must use professional drawing software such as Adobe Illustrator, CorelDraw, and gimp to display the image. This format is not supported by Windows plotting and ACDSee on your computer. This is understandable, because SVG is a standard for Internet films. So let's take a look at how to display it in a browser-unfortunately, this is still not as easy as opening a jpg or GIF.

Different browsers have different support for SVG. In general, ie, which still occupies the largest market share, is not supported by other mainstream browsers, firefox, chrome, Safari, and opera, which have the second market share, have different levels of support for the SVG standard. IE6, 7, and 8 have no native support for SVG and require specialized plug-ins (such as Adobe SVG Viewer) for display. Ie9, which is currently in the technical preview version, will be supported. Considering that Internet Explorer once occupies a monopoly position and Microsoft has its own competitive VML technology, this "lag" is not surprising.

However, this situation is changing rapidly in the rapidly growing browser market. So it is best to see which of the following display methods is supported by your browser.

  1. Use the label.


    Use SVG in the same way as traditional Internet image formats (currently only supported by Chrome, Safari, and opera ).

  2. Use the <embed> label.

    <Embed src = "Sun. SVG" width = "300" Height = "100"
    Type = "image/SVG + XML"
    Pluginspage = "http://www.adobe.com/svg/viewer/install/"/>
    The value of the pluginspage attribute is the installation address of Adobe SVG Viewer, a plug-in developed by Adobe for browsers that do not support SVG. In January 1, 2009, Adobe terminated its support for the product.

  3. Use the <Object> label.
    <Object Data = "Sun. SVG" width = "300" Height = "100" type = "image/SVG + XML" codebase = "http://www.adobe.com/svg/viewer/install/"/>
  4. Use the <IFRAME> label.
    <IFRAME src = "Sun. SVG" width = "300" Height = "100" border = "0" style = "border-width: 0"> </iframe>

The following is a page for testing whether the browser supports various SVG-based HTML methods.Code. The sun. SVG file and the page are saved in the same directory.

Listing 2. Test the browser's support for SVG

 
         SVG in HTML    1. use the & lt; IMG & gt; label 

2. use the & lt; embed & gt; label

3. use the & lt; object & gt; tag

4. use the & lt; IFRAME & gt; tag

 

Dynamic Functions

If you only reference SVG as an image, you only use its static function. We are more interested in applying its dynamic functions. The dynamic functions of SVG include two aspects. One is animation, and the other is Script Programming.

Animation

SVG is designed with support for animation. This is achieved through another W3C animation language siml (Synchronized Multimedia Integration Language. When siml is applied, it is very closely integrated with SVG. Like SVG, It is a declarative markup language that defines animation behavior through elements and attributes. Here is only a simple example, which is not described in detail. Because the browser has limited support for it, and its declarative nature also limits the expressiveness, it is not as flexible as using script Custom Animation.

Listing 3. animation implemented with siml

<? XML version = "1.0" standalone = "no"?> <! Doctype SVG public "-// W3C // dtd svg 1.1 // en" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <SVG xmlns = "http://www.w3.org/2000/svg"> <polygon points = "50,100 100,100, 50" stroke = "#660000" fill = "# cc3333"> <animatetransform attributename = "transform" begin = "0 s" dur = "10 s" type = "Rotate" from = "0 0 0 "to =" 360 60 60 "repeatcount =" INDEFINITE "/> </polygon> </SVG>

 

The polygon element specifies to draw a multi-deformation. Three vertices are given here, so it is a triangle. Save the above Code as an SVG file and reference it on a page. If your browser supports siml, a red triangle is displayed on the screen; if your browser only supports SVG, you will see a static red triangle.

Script programmability

SVG is an XML file. The Dom and sax models used for XML programming are also applicable to it. Because SVG is designed for the Internet, accessing it through JavaScript and Dom is the most important application mode. We are already familiar with the dynamic modification of HTML through JavaScript and Dom. We can also dynamically create, modify, and delete images in the browser. This will also be the focus of SVG in the future.

To demonstrate these dynamic functions, we adopt a different way of using SVG on pages -- Directly Writing SVG source text in XHTML (XML version of XML, the above four methods of SVG definition are stored in another file different from the page. There are two reasons for doing so. First, in browsers that support XHTML and SVG, you can directly access and modify SVG through JavaScript. Second, in the future standard HTML 5 of the Internet, SVG can be defined in HTML directly, just like other HTML elements.

The following examples can be run in Firefox, but ie cannot be used. It is only later than version 9 that IE will add support for XHTML (currently, ie only supports XHTML as HTML interpretation), and again shows the slowness of Embracing public standards.

The first example is a progress bar. When the following XHTML page is loaded in Firefox, a green motion progress bar is displayed.

Figure 1. progress bar example

Listing 4. progress bar code

<HTML xmlns = "http://www.w3.org/1999/xhtml"> 

 

You need to describe the XHTML.

<HTML xmlns = "http://www.w3.org/1999/xhtml">
The root element of XHTML is an HTML element. The xmlns attribute specifies the XHTML namespace.

<SVG xmlns = "http://www.w3.org/2000/svg" version = "1.1" viewbox = "0 0 100 100" style = "border: 1px solid; width: 100px; Height: 100px;">
Insert SVG elements directly in XHTML and specify other attributes such as namespaces.

Viewbox defines the coordinate space visible to the vector graph. The four numbers are the X coordinate of the origin, Y coordinate, width and height of the plane. The coordinate space of SVG conforms to the Convention of the specified screen space in the computer. The square direction of the X axis is right, and the square direction of the Y axis is downward.

The style attribute specifies the appearance characteristics of SVG elements. Like HTML, SVG can apply CSS to define the appearance and has some special features:

  1. JavaScript code in XHTML is included in/* <! [CDATA [*/and/*]>.

    This is not required in HTML files. Because the JavaScript code in the <SCRIPT> tag in HTML is interpreted as CDATA (a type in character data, XML, used to contain arbitrary character data ); in XHTML, the part of the <SCRIPT> label is interpreted as pcdata (parsed character data, also a type in XML, which is a mixture of character data and element content ), therefore, we also need to check the XML syntax, while JavaScript code obviously does not conform to the XML tag definition syntax. The solution is to manually add it out of the code! [CDATA [and]> annotation, so that the XML syntax validator ignores this section. However, this will cause the second problem. Some browsers do not know CDATA annotation, so these codes cannot pass the Javascript syntax check. Therefore, we add the Javascript Annotation on both sides of the CDATA annotation. In this way, the code in the <SCRIPT> label can be recognized by both the XML syntax check and the JavaScript engine.

  2. The <SVG> tag contains one <G> tag and two <rect> tags.

    The G element is used for grouping. Grouping not only makes the content structure of SVG clear, but also objects in the same group can be operated collectively. The rect element represents a rectangle. the X, Y, width, and height attributes specify the abscissa, ordinate, and width and length of the top left vertex of the rectangle, respectively. The stroke attribute specifies the line color of the image's outer frame. We use the first hollow rectangle to show the outer frame of the progress bar, and the second solid green rectangle to show the progress of the change. To facilitate access in the script, we set the ID attribute of the green rectangle.

  3. Code Description

    In JavaScript scripts, we use Dom to obtain the green rectangle object and modify its width attribute. The usage of getelementbyid and setattribute is similar to that in HTML. It is worth noting that some methods we use when operating HTML do not exist in XML, for example, getelementsbyname of the element based on the name.

    In this example, the first three points are particularly difficult to set, but these are not necessary in HTML 5, which is gaining more and more support and will soon become the realistic standard of the Internet. In HTML 5, you do not need to specify the namespace in HTML and SVG elements. SVG and various tags are automatically recognized. The javascript code will be the same as the current HTML page. You do not need to add the CDATA Annotation on both sides.

Event

The elements in SVG also support user interface events. Therefore, we can change the graphics in SVG through various events triggered by the mouse and keyboard. This allows you to interact with various images on the entire page without the flash plug-in. The following uses several examples to illustrate the use of events, using the methods defined in the dom3 event specification.

Analog control

Standard controls such as single-choice buttons, check boxes, and drop-down lists in HTML provide various friendly methods for users to enter and display data. In the past, we could only "use" them. Now we can simulate or even create new controls. Let's first simulate a simple single-choice button graphics and behavior.

Figure 2. Simulate radio button

Listing 5. Code of the simulated radio button 1

<HTML xmlns = "http://www.w3.org/1999/xhtml"> 

 

Code Description:
SVG

There are three circle elements, two of which are circles of the empty option, and the third is used to mark the selected status. We have read several attributes that control the size and position in circle before. The stroke-width attribute is used to control the width of the line in the drawing's outer frame. The name attribute is customized to associate a group of radio buttons.

Text elements must be used to embed text in SVG. The X and Y attributes are used to control the text position. X is the coordinate of the Left end, and Y is the coordinate of the lower end.

Of course, the above just simulates the appearance of a single button to respond to the mouse click, the real control must also include read and write data. To this end, we will extend the above example to provide a single button that can be used separately ".

Figure 3. More comprehensive simulated radio button

The code for implementing such a single button is long and attached to the reference resource. The Code contains detailed comments.

Finally, a more complex and interesting example is provided to demonstrate the possibility of a vivid image application created by SVG. A circle, two points, and an arc form a famous symbol on the Internet. This simple image can not only be seen as a face, but also show different expressions from smiling faces to crying faces by changing the shape of the arc. It shows that the human brain recognizes the complex behavior of human faces in a modular and fuzzy way. This abstract processing method also provides a good occasion for displaying SVG functions. We first draw such a simplified face, then create a slide control, and finally use the drag slide to control the bending degree and direction of the arc in the face. If we interpret the height of the slider as a symbol of a person's pressure, we can see how the human expression changes with the change of pressure. This code is long and can be downloaded from reference resources.

Figure 4. A more complex example

 

Summary

This article introduces the basic concept of an XML-based vector graph technology SVG for the Internet, and shows the flexibility and broad application prospects of this technology when it is combined with JavaScript through some examples.

Reference resources

Download

description name size download method
Sample Code sample.zip 5 kb HTTP
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.