How to draw an SVG file on an HTML5 canvas?

HTMLWeb DevelopmentFront End Technology

To draw SVG onto canvas, you need to use SVG image. Firstly, use the <foreignObject> element which contains the HTML. After that, you need to draw the SVG image into the canvas.

Example

You can try the following code to draw an SVG file on an HTML canvas

<!DOCTYPE html>
<html>
   <head>
      <title>SVG file on HTML Canvas </title>
   </head>
   <body>
      <canvas id="myCanvas" style="border:2px solid green;" width="300" height="300"></canvas>
      <script>
         var canvas = document.getElementById('myCanvas');
         var ctx = canvas.getContext('2d');
         var data = '<svg xmlns="http://www.w3.org/2000/svg" width="300"
         height="200">' +
            '<foreignObject width="100%" height="100%">' +
               '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:50px">' +
                  'Simply Easy ' +
                  '<span style="color:blue;">' +
                  'Learning</span>' +
               '</div>' +
            '</foreignObject>' +
         '</svg>';
         var DOMURL = window.URL || window.webkitURL || window;
         var img1 = new Image();
         var svg = new Blob([data], {type: 'image/svg+xml'});
         var url = DOMURL.createObjectURL(svg);
         img1.onload = function() {
            ctx.drawImage(img1, 25, 70);
            DOMURL.revokeObjectURL(url);
         }
         img1.src = url;
      </script>
   </body>
</html>

Output

raja
Updated on 16-Dec-2021 10:23:29

Advertisements