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.


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

Live Demo

<!DOCTYPE html>
      <title>SVG file on HTML Canvas </title>
      <canvas id="myCanvas" style="border:2px solid green;" width="300" height="300"></canvas>
         var canvas = document.getElementById('myCanvas');
         var ctx = canvas.getContext('2d');
         var data = '<svg xmlns="" width="300"
         height="200">' +
            '<foreignObject width="100%" height="100%">' +
               '<div xmlns="" style="font-size:50px">' +
                  'Simply Easy ' +
                  '<span style="color:blue;">' +
                  'Learning</span>' +
               '</div>' +
            '</foreignObject>' +
         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);
         img1.src = url;
Published on 07-Feb-2018 18:44:31