0

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.

  • Possible duplicate of [Convert canvas to an image with JavaScript](https://stackoverflow.com/questions/16301449/convert-canvas-to-an-image-with-javascript) – Carsten Løvbo Andersen Sep 05 '19 at 11:02
  • It seems that using canvas is redundant in your case. You already have image elements in `images` variable. So what you need is just insert them explicitly into the DOM. And no canvas operation is needed here. – hindmost Sep 05 '19 at 11:11

1 Answers1

0

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

Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43