'Replace HTML5 canvas Elements With img Elements

Want to replace the canvas element to image element.

Already tried to convert the canvas to image using jquery. But the empty image is displaying without any images.

<script>
        function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        // get num of sources
        for(var src in sources) {
          numImages++;
        }
        for(var src in sources) {
          images[src] = new Image();
          images[src].onload = function() {
            if(++loadedImages >= numImages) {
              callback(images);
            }
          };
          images[src].src = sources[src];
        }
      }
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var sources = {
        image1: 'Group 1.png',
        image2: 'Rectangle 5.png',
        image3: 'Motif_2.png',
        image4: 'body_design_2.png'
      };

      loadImages(sources, function(images) {
        context.drawImage(images.image1, 0, 0, 484, 984);
        context.drawImage(images.image2, 42, 0, 400, 747);
          context.drawImage(images.image3, 0, 0, 484, 984);
          context.drawImage(images.image4, 42, 0, 400, 747);
      });
        </script>
        <script>
            $(document).ready( function(e)
            {
                $('canvas').each( function(e)
                {
                    var image = new Image();
                    image.src = this.toDataURL("image/png");

                    $(this).replaceWith(image);
                });
            });
        </script>

Replace the canvas element to image element.Any solution regarding this question.



Solution 1:[1]

Here is a way to do this:

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

ctx.fillRect(50, 50, 50, 50);

var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);
canvas {
  border: 1px solid gray;
}
<canvas id="canvas1" width="200" height="200"></canvas>

Click Here for sample

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anurag Srivastava