How to Draw SVG content to Canvas in HTML5

Source: Internet
Author: User
Tags base64 comparison

SVG and canvas are two completely different modes of drawing application on HTML5, and both of them have advantages and disadvantages, but they are not incompatible with each other, especially the SVG content can be directly drawn on the canvas function, so that the two can be perfectly fused together, Allow canvas to enjoy the existing rich SVG material, without losing the SVG vector stepless scaling characteristics.

The format data for the normal picture is the data:image/png type, and the SVG format data type is Data:image/svg+xml type, and the following illustration is the effect of dragging the HT for Web topology diagram into the SVG-formatted picture:


The following is a small example, showing the loading of an SVG image, divided into seven basic zoom rendering effect, you can see canvas rendering SVG can maintain its vector distortion characteristics

Function draw () {    var img = new image ();    
 img.src =  ' Chart.svg ';
    document.body.appendchild (IMG);     img.onload = function () {        var
 canvas = document.getelementbyid (' canvas ');         var g = canvas.getcontext (' 2d ');   
       var width = img.clientWidth * 1.5;         var height = img.clientHeight * 1.5;                    
      var x = 2;
        var y = 2;         for (var i=0;  i<7; i++) {            g.drawimage (
Img, x, y, width, height);
            x += width + 2;
            width /= 2;
            height /= 2;         }          
       }; }


Referring to the fusion of canvas and SVG, we will use the HT for Web vector function to display a mobile phone battery charging progress of the example, the entire cell phone battery static part of We by loading a simple SVG material to achieve, and the dynamic change in the charging part, we use a progressive color of the HT rectangle element to describe , the length of the rectangle is determined by the dynamic binding function of the HT vector data, which is converted to the length information according to the percentage of the charging progress, finally the dynamic charging effect is achieved by the simulation data of the timer:


Ht. Default.setimage (' Battery ',  {    width: 64,     height: 
    comps: [            {             type:  ' rect ',              rect: {                 func: function (data) {                     return [5, &NBSP;25,&NBSP;50*DATA.A (' percent '),  16]                  }             } ,             background:  ' Red ',              gradient:  ' spread.vertical '          },                                  {             type:  ' image ',              name:  ' Battery.svg ',              relative: true,          
&NBSP;&NBSP;&NBSP;RECT:&NBSP;[0,&NBSP;0,&NBSP;1,&NBSP;1] &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} &NBSP;&NBSP;&NBSP;&NBSP]});                 Var node = new ht.
Node ();
Node.setposition (80, 150);
Node.setimage (' battery '); NODE.S ('Image.stretch ',  ' uniform ');
Node.a (' percent ',  0);
Datamodel.add (node);    graphview.seteditable (true); SetInterval (function () {&NBSP;&NBSP;&NBSP;&NBSP;PERCENT&NBSP;=&NBSP;NODE.A (' percent ')  + 0.02;      if (percent > 1) {        percent =
 0;
&NBSP;&NBSP;&NBSP;&NBSP}     node.a (' percent ',  percent); },&NBSP;16);


SVG draws to canvas also has a special application scenario, which is to describe HTML elements in SVG through the foreignobject characteristics of SVG, and then canvas to draw SVG, You can draw the HTML content described in Foreignobject to Canvas, see Https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM _objects_into_a_canvas instance, which uses a BLOB to set IMG's src as a URL is a more bizarre technical point, but from the above we can actually convert the entire SVG content into data:image/svg+xml; Base64 content can be passed as the URL of src, so I modified the example, using Btoa (data) to convert SVG content to Base64 way to set IMG.SRC, so that the way is easier to understand, example code and effects are as follows: http:// V.youku.com/v_show/id_xodg0mtu4njey.html



function draw () {    var canvas = 
document.getElementById (' canvas ');
    var ctx = canvas.getcontext (' 2d ');
    var data =  ...;
    var img = new image ();     img.onload = function  ()  {      
  ctx.drawimage (img, 0, 0);     };               
  img.src =  ' Data:image/svg+xml;base64, '  + btoa (data); }




Comparison between Canvas and SVG in HTML 5

Both Canvas and SVG allow you to create graphics in the browser, but they are fundamentally different.

Svg

SVG is a language that uses XML to describe 2D graphics.

SVG is xml-based, which means that every element in the SVG DOM is available. You can attach a JavaScript event handler for an element.

In SVG, each drawn graphic is treated as an object. If the properties of the SVG object change, the browser can reproduce the graphic automatically.

Canvas

Canvas uses JavaScript to draw 2D graphics.

Canvas is rendered in pixels.

In canvas, once the graphic has been drawn, it will not continue to get the attention of the browser. If its position changes, the entire scene needs to be redrawn, including any object that may have been covered by the graphic.


A comparison between Canvas and SVG

The following table lists some of the differences between canvas and SVG.

Canvas

Dependent resolution
Event Processor not supported
Weak text rendering capabilities
Ability to save the resulting image in. png or. jpg format
Ideal for image-intensive games, where many of the objects are frequently redrawn

Svg

Non-dependent resolution
Support Event handlers
Best for applications with large rendering areas (Google Maps, for example)
High complexity slows down rendering (any application that uses DOM too much is not fast)
Not suitable for game application

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.