Scalable vector graphics in HTML5. Scalable Vector Graphics (SVG) - Exploration Graphics Tags

Vector graphics are widely used in print. But for websites, we can also use it with SVG ( Scalable Vector Graphic - scalable vector graphics). According to the W3.org specification, SVG is defined as:

A language for describing two-dimensional graphics in XML. SVG allows the use of three types of objects: vector graphic shapes (for example, paths made up of straight lines and curves), images, and text.

Even though since August 2011 SVG has been included in the W3C recommendations, this technology practically not used in web projects, although it has a number of advantages over bitmaps. In this series of tutorials, we will introduce how to work with SVG elements on web pages.

Benefits of SVG

Resolution Independence

Raster images are resolution dependent. Graphics become unpresentable when resized to certain scales. With vector graphics, such a situation is impossible in principle, since everything is represented by mathematical expressions that are automatically recalculated when the scale changes, and the quality is preserved in any conditions.

Reducing the number of HTTP requests

SVG can be embedded directly into an HTML document using the svg tag, so the browser doesn't need to be prompted to serve the graphics. This approach has a good effect on the loading characteristics of the website.

Styles and scripts

Embedding with the svg tag also makes it easy to style graphics with using CSS. You can change object properties such as background color, transparency, borders, and so on. Similarly, graphics can be manipulated with JavaScript.

Easy to edit and animate

SVG objects can be animated using CSS or JavaScript. Also, SVG objects can be modified using a text editor.

Smaller file size

SVG has a smaller file size compared to raster graphics.

Basic SVG Shapes

According to the specification, we can draw several basic shapes: line, polyline, rectangle, circle, ellipse. All elements must be inserted in the tag ... . Consider the basic elements in detail.

Line

An element is used to draw a line in SVG . It draws a segment for which two points must be defined: the beginning and the end.

The start of the segment is defined by the x1 and y1 attributes, and the end point is defined by the coordinates in the x2 and y2 attributes.

There are also two other attributes (stroke and stroke-width) that are used to define the color and width of the line, respectively.

This object is similar to , but with the element You can draw multiple lines at once.

Element Contains the points attribute, which is used to specify the coordinates of the points.

Rectangle rendered with element . We need to define the width and height.

To draw a circle, use the element . In the following example, we create a circle with a radius of 100 , which is defined in the r attribute:

The first two attributes cx and cy define the coordinates of the center. In the above example, we have set both coordinates to 102. The default value is 0.

To draw an ellipse, use the element . It works just like a circle, but we can specifically set the x and y radii using the rx and ry attributes:

Element Displays polyhedral shapes such as a triangle, a hexagon, and so on. For example:

Using the editor for vector graphics

Rendering simple SVG objects to HTML is easy. However, as the complexity of the object increases, this practice can lead to a large amount of work to be done.

But you can use any editor for vector graphics (for example, Adobe Illustrator or inkscape) to create objects. If you own such a tool, it is much easier to draw the necessary objects in them than to encode graphics in an HTML tag.

You can copy commands for vector graphics from a file to an HTML document. Or, you can embed the .svg file using one of the following elements: embed , iframe , and object .

The result will be the same.

Browser Support

SVG has good support in most modern browsers, with the exception of IE version 8 and earlier. But the task can be solved using the JavaScript library. To make things easier, you can use the ReadySetRaphael.com tool to convert SVG code to Raphael format.

First, we load and include the library in an HTML document. Then we load the .svg file, copy and paste the resulting code into the function after loading:

In the body tag we place the following div element with the ID rsr .

And everything is ready.

In the next tutorial in the series, we'll look at how to style SVG objects in CSS.

(Overview article following the software development conference in Yekaterinburg and other presentations. Video version of the report in Yekaterinburgsee techdays.ru )

What is HTML5 Canvas and SVG?

HTML5 Canvas

– the element is a canvas for rendering bitmap graphics. In fact, this is an empty block given dimensions, on which you can draw using special APIs for JavaScript.

The API includes 45 special methods and 21 attributes used to display graphic primitives, set styles, transforms, access individual pixels, project images and videos.

Myself the element is defined directly in the HTML5 specification. The API for it is described in a separate document -- HTML Canvas 2D Context .

SVG

Music Can Be Fun

A beautiful musical visualization game (http://musiccanbefun.edankwan.com/).

SVG Scheme Examples

Diagram of the Human Skeleton, Periodic Table of Chemical Elements, and Respiratory System (http://ie.microsoft.com/testdrive/Graphics/RealWorldDataAndDiagrams/Default.xhtml).

Yandex Maps

A closer real-life example is using SVG when rendering routes (if the browser supports it). See also the "Maps and SVG" talk from our HTML5 Camp.

More examples:

  • Beauty of the Web http://www.beautyoftheweb.com/ - real sites from the real world
  • Dev: unplugged http://contest.beautyoftheweb.com/ - projects participating in the HTML5 application competition

Difference between Canvas and SVG

In various scenarios, either Canvas or SVG may be better suited for dynamic rendering of graphics - we will return to this issue at the end. In the meantime, let's focus on the key differences between one and the other:

Canvas SVG
Format Raster Vector
Scaling
Access

Individual Pixel Access (RGBA)

Individual element access (DOM)

Indexability and Accessibility

Only the final raster is visible (you can't select shapes, text, etc.) - bad for Accessibility

You can see the structure (for example, pull out the entire text)

Stylization

Visual styles are set when rendering via API

Visual styles are set by attributes, you can include CSS

Programming

JS API for working with primitives

DOM for working with elements

Update

To update - draw over or completely redraw

It is possible to change individual elements

Developments

There is no easy way to handle mouse events. The objects under the cursor must be defined manually.

Events from the mouse through DOM are easily hung up, are processed automatically.

Code integration

JS code separate from Canvas

You can include JS inside

These differences must be taken into account when using a particular technology for data visualization. For example, drawing a graph of a function can be easier with Canvas, while displaying tooltips (with the definition of an object under the mouse pointer) is easier with SVG.

In practice, however, there are already a number of ready-made libraries for data visualization that partially offset these differences.

I will not go into the basics of working with each of the technologies, as an introductory I recommend the report by Vadim Makeev (Opera) from the HTML5 Camp “Dynamic Graphics: Canvas and SVG”.

See also reports MIX 2011:

Image Processing with Canvas

One of the notable features of Canvas is that this technology provides pixel-by-pixel access to the displayed data and allows various graphic elements, including video, to be projected onto the canvas.

A good example of where this is needed is in an image processing/analysis task.

Processing.js offers two approaches to visualization description: intermediate code, further parsed by the library itself (in a separate file or inside the page) and explicit JavaScript code.

For example, to draw a fractal Mandelbrot set, you can use either the option listed on the page with the corresponding example, or the following JavaScript code:

var xmin = -2.5; varymin = -2; var wh = 4; function sketchProc(processing) ( processing.setup = function () ( processing.size(200, 200); processing.noLoop(); ); processing.draw = function () ( processing.loadPixels(); var maxiterations = 200; var xmax = xmin + wh; var ymax = ymin + wh; var dx = (xmax - xmin) / (processing.width); var dy = (ymax - ymin) / (processing.height); var y = ymin; for (var j = 0; j< processing.height; j++) { var x = xmin; for (var i = 0; i < processing.width; i++) { var a = x; var b = y; var n = 0; while (n < maxiterations) { var aa = a * a; var bb = b * b; var twoab = 2.0 * a * b; a = aa - bb + x; b = twoab + y; if (aa + bb >16.0) ( break ; ) n++; ) if (n == maxiterations) processing.pixels.setPixel(i+j*processing.width, 0); else processing.pixels.setPixel(i+j*processing.width, processing.color(n*16 % 255)); x += dx; ) y += dy; ) processing.updatePixels(); ); ) var canvas = document.getElementById("myCanvas" ); var p = new Processing(canvas, sketchProc);

You can try it yourself here: http://silverbook.ru/projects/html5datavisualization/demo3-processingjs.htm (copy the code, paste it into the console and execute).

JavaScript InfoVis Toolkit (JIT)

To display data, JIT accepts raw values ​​as JSON:

var json = ( "label" : ["label A" , "label B" , "label C" , "label D" ], "values" : [ ( "label" : "date A" , "values" : ) , ( "label" : "date B" , "values" : ), ( "label" : "date E" , "values" : ), ( "label" : "date F" , "values" : ), ( "label" : "date D" , "values" : ), ( "label" : "date C" , "values" : )] ); var pieChart = new $jit.PieChart(( injectInto: "infovis" , animate: true , offset: 30, sliceOffset: 0, labelOffset: 20, type: "stacked:gradient" , showLabels:true , resizeLabels: 7, Label: ( type: "Native" , size: 20, family: "Arial" , color: "white" ), Tips: ( enable: true , onShow: function (tip, elem) ( tip.innerHTML = " "+ elem.name + ": " + elem.value; ) ) ));

it is enough to call drawing:

PieChart.loadJSON(json);

jQuery Sparklines

Map visualization with SVG

Let's move on to SVG and start with a simple example. Imagine that you need to display some data on a map of regions, what is the easiest way to do this?

If you have a ready-made map in the form of SVG (I took a map of Russia from the Wikipedia site), then this is done very simply - it is enough that each region has its own unique id inside the SVG document, then we insert the map as inline svg and color it with a simple code in the right color:

var SverdlovskOblast = document.getElementById("SverdlovskOblast" ); SverdlovskOblast.style.fill = "#fe3300" ;

If you do the same in a loop, then you can already color not just the region, but the whole region or even the whole country:

var data = [(id: "KurganOblast" , value: 30), (id: "SverdlovskOblast" , value: 200), (id: "TyumenOblast" , value: 75), (id: "KhantiaMansia" , value: 100 ), (id: "YamaloNenetsAutDistrict" , value: 20), (id: "ChelyabinskOblast" , value: 150)]; for (var i = 0; i< data.length; i++) { var item = data[i]; var region = document.getElementById(item.id); region.style.fill = RGBtoHex(item.value, 0, 0); }

Libraries for visualizing data with SVG

As I said, both Canvas and SVG are suitable for solving the traditional task of visualizing numerical data in the form of graphs and charts. In both cases, this is fairly easy to do with the appropriate libraries.

We have already looked at the Canvas examples, now let's look at several libraries for working with SVG. (This is also not an exhaustive list, but rather high-quality and popular solutions.)

Raphael

To add a simple pie chart enough code like this:

var r = Raphael("chart" , 640, 480); var pie = r.g.piechart(320, 240, 100, );

With a few additional operations, you can add a legend, chart captions, and interactive tooltips:

var r = Raphael("chart" , 640, 480); r.g.txtattr.font = "12px "Fontin Sans", Fontin-Sans, sans-serif"; r.g.text(320, 100, "Interactive Pie Chart" ).attr(("font-size" : 20)); var pie = r.g.piechart(320, 240, 100, ,
(legend: ["%%.%% – Enterprise Users" , "IE Users" ], legendpos: "west" ,
href: ["http://raphaeljs.com" , http://g.raphaeljs.com]});
pie.hover(function () ( this .sector.stop(); this .sector.scale(1.1, 1.1, this .cx, this .cy); if (this .label) ( this .label.stop(); this .label.scale(1.5); this .label.attr(("font-weight" : 800)); ) ), function () ( this .sector.animate((scale: ), 500, "bounce" ) ; if (this .label) ( this .label.animate((scale: 1), 500, "bounce" ); this .label.attr(("font-weight" : 400)); ) ));

Similarly, you can display other types of charts using the appropriate methods. See examples directly on the extension site http://g.raphaeljs.com/

HighchartsJS

The library API makes it quite easy to generate a chart from data in JSON:

var chart1 = new Highcharts.Chart(( chart: ( renderTo: "charts" , defaultSeriesType: "bar" ), title: ( text: "Fruit Consumption" ), xAxis: ( categories: ["Apples" , "Bananas" , "Oranges" ] ), yAxis: ( title: ( text: "Fruit eaten" ) ), series: [( name: "Jane" , data: ), ( name: "John" , data: )] ));

With a slightly more complex script, you can specify additional details, for example, display a legend, set up tooltips:

var chart = new Highcharts.Chart(( chart: ( renderTo: "charts" , defaultSeriesType: "area" , spacingBottom: 30 ), title: ( text: "Fruit consumption *" ), subtitle: ( text: "* Jane\"s banana consumption is unknown", floating: true , align: "right" , verticalAlign: "bottom" , y: 15 ), legend: ( layout: "vertical" , align: "left" , verticalAlign: "top" , x: 150, y: 100 , floating: true , borderWidth: 1, backgroundColor: "#FFFFFF" ), xAxis: ( categories: ["Apples" , "Pears" , "Oranges" , "Bananas" , "Grapes" , "Plums" , "Strawberries" , "Raspberries" ] ), yAxis: ( title: ( text: "Y-Axis" ), labels: ( formatter: function () ( return this .value; ) ) ), tooltip: ( formatter: function () ( return " "+this.series.name+"
" + this .x +": " + this .y; ) ), plotOptions: ( area: ( fillOpacity: 0.5 ) ), series: [( name: "John" , data: ), ( name: "Jane" , data: )] ));

If necessary, you can replace the default styles with your own.

What to choose: Canvas or SVG?

As you can see from the examples above, both technologies are often suitable for data visualization tasks. Many things are done in a similar way. In cases where pixel-by-pixel output is needed, Canvas is obviously better suited. Where the diagram breaks into separate objects that need to be interactive, SVG is better suited.

Canvas is better
  • Editing bitmap graphics
  • Applying effects to graphics/video
  • Raster graphics generation (data visualization, fractals, function graphs)
  • Image analysis
  • Game graphics (sprites, background, etc.)
SVG is better
  • Scalable Interfaces
  • Interactive interfaces
  • Diagrams, schemes
  • Vector Image Editing

In graphical form, this can be represented as follows:

Finally, another important cut that is also important to consider when choosing a technology is rendering performance when using Canvas and SVG:

In practice, canvas works better with small render area sizes and a large number of objects, in SVG it is better suited when scaling or displaying on a large screen and not too in large numbers outputted objects at a time.

This conclusion follows from the report of the chairman of the board of Bashneft, announced to the general meeting of shareholders of the company, a copy of which was made available to the editors.

It follows from the document that as a result of geological exploration, in 2018, 81 productive deposits were discovered with reserves of 19 million tons.

At the same time, the use of highly effective geological and technical measures and the introduction of modern technologies for enhanced oil recovery made it possible to maintain oil production at mature fields in Bashkiria at the 2017 level of 15 million tons following the results of 11 months. The total volume of production for the specified period amounted to 17.3 million tons of oil.

The report also notes that the creation of a single production chain with the production and processing complex of Rosneft has increased the efficiency of the Ufa refineries and led to a reduction in operating and logistics costs. In particular, the production of Euro-6 gasoline has been mastered and the industrial production of road bitumen in accordance with the new GOST has begun.

The volume of retail sales at Bashneft filling stations for 11 months of 2018 increased by 13.2 percent compared to the same period last year and reached 1.7 million tons.

To implement the strategy in the field of petrochemistry, petrochemical production is being modernized. So, in May 2018, Ufaorgsintez put into operation new installation production of cumene - raw materials for the manufacture of paints, solvents, various polymers used in the automotive industry, medicine and pharmacology. Next in line is the reconstruction of the aromatics production complex at Ufaneftekhim, the construction of new olefin production units at Ufaorgsintez.

The consolidated indicator of operating profit for 9 months of 2018 increased by 22.6 percent compared to the same period in 2017 and amounted to 135.5 billion rubles. Bashneft's net profit reached 74.6 billion rubles, which is 73.5 percent more than in the same period last year.

During the third quarter, Bashneft paid shareholders dividends announced at the annual meeting in June 2018 in the amount of 28.2 billion rubles, and the total amount of dividends paid since the beginning of the year amounted to 43 billion rubles.

At the same time, the level of the company's net debt decreased and as of September 30, 2018 amounted to 40.1 billion rubles (as of the same date in 2017, this figure was 104.7 billion rubles).

At the same time, during the reporting period, tax deductions to the budget of Bashkortostan, taking into account a one-time income tax payment, increased by 1.5 times compared to the same period last year and amounted to 50.5 billion rubles.

There is a tag to include an image in a specific place on the page. . This tag has a required parameter: SRC="", and several optional ones. The SRC="" parameter tells the browser where to look for the graphic and should have as its value the URL of the resource where the graphic file is located. In the simplest case, this file will be placed in the root directory or in the IMG folder of your site. Optional parameters:

The ALT="" parameter contains an inscription as a value that tells about the content of the image for those visitors whose browsers do not support graphics or work in disabled graphics mode. The same inscription appears when you hover the mouse over the image.

The parameters WIDTH="" HEIGHT="" have as values ​​the dimensions of the image in terms of width and height in pixels. It is desirable to specify these parameters in the page code so that the browser leaves space for the image in advance, then, when loading, the page will "twitch" less. In addition, these parameters can be used to adjust the size of the picture in the browser window.

The BORDER="" parameter draws a border around the image. The value is a number indicating the width of the frame in pixels.

The ALIGN= parameter determines the position of the image on the page, and can take values ​​TOP - aligns the top border of the image with the highest element of the current line, TEXTTOP - aligns the top border of the image with the highest text element of the current line, MIDDLE - aligns the middle of the image with the baseline of the current line , ABSMIDDLE - aligns the middle of the image to the middle of the current line. BASELINE or BOTTOM - aligns the bottom border of the image with the baseline of the current line, ABSBOTTOM - aligns the bottom border of the image with the bottom border of the current line, HSPACE= - defines the horizontal indent, VSPACE= - defines the vertical indent.

Tag syntax:

Ticker

The running line is set by the tag .

The attributes of this tag are bgcolor - the background color of the scrolling line, height - the height of the line, width - the width of the line.

Direction - sets the direction of movement of the ticker - direction="left" (right, up, down) - movement to the left (right, up, down).

Behavior - string behavior - behavior="scroll" (slide, alternate). Scroll - normal scrolling (you can not prescribe it, it is the default)



Slide - scrolling with a stop, the line runs to the edge and stops. If the loop parameter is used simultaneously with behavor="slide" , then the line will scroll the set number of times and stop at the edge. Alternate - the line will move from edge to edge.
Scrollamount - line speed, scrollamount="1". It can take values ​​from 1 to 10. 1 is the slowest movement, 10 is the fastest.

Tag syntax: text

Modern web browsers can play video and audio files in a variety of formats. To do this, they use built-in players (plug-ins, ActiveX controls) or external player programs. You can insert sound or video into an HTML document using various tags:

- to insert background sound;

- to insert video in AVI format;

- to insert sound and video files;

- to insert sound and video files.

When deciding to embed audio and/or video into an HTML document, keep in mind that the corresponding files are quite large. The most popular on the web now are MP3, WMA, AIFF, AU, RealAudio (ra and ram), MP4, MIDI and MPEG, MOV video formats. The WAV audio format and AVI video format are rarely used on the Internet.