virtual canvas putimagedata not working

1.2k Views Asked by At

Am new to concept of virtual canvas, any idea why the below code does not work?

    <script type="text/javascript">

          $(document).ready(function () {


              var c1 = document.createElement('canvas');
              var ctx1 = c1.getContext("2d");
              var c2 = document.getElementById('Canvas2');
              var ctx2 = c2.getContext("2d");
              c1.width = c2.width;
              c1.height = c2.height;

              img1 = new Image();
              img1.src = 'A1.png';
              img1.onload = function () {
                  ctx1.drawImage(this, 0, 0);
              };


              imgdata = ctx1.getImageData(0, 0, c2.width, c2.height);

              ctx2.putImageData(imgdata, 0, 0);


          });

      </script>  




   <canvas id="Canvas2"  style="display:block;position:absolute;background-color:transparent;border:1px solid red;">
   Your browser does not support the HTML5 canvas tag.
   </canvas>

The concept works if i draw Rectangle or any other objects but when i am loading images it does not display the images loaded on virtual canvas. As below example works fine.

  $(document).ready(function () {


      var c1 = document.createElement('canvas');
      var ctx1 = c1.getContext("2d");
      var c2 = document.getElementById('Canvas2');
      var ctx2 = c2.getContext("2d");
      c1.width = c2.width;
      c1.height = c2.height;


      ctx1.fillRect(0, 20, 20, 20);

      imgdata = ctx1.getImageData(0, 0, c2.width, c2.height);

      ctx2.putImageData(imgdata, 0, 0);


  });

1

There are 1 best solutions below

1
On BEST ANSWER

You must also wait with getImageData etc. until the image has loaded, so move everything that needs to be done after the image has loaded inside the onload handler (or wrap them in a function called from onload):

img1.onload = function () {

     ctx1.drawImage(this, 0, 0);

     imgdata = ctx1.getImageData(0, 0, c2.width, c2.height);

     ctx2.putImageData(imgdata, 0, 0);
};

If you don't then the image may not be loaded and drawn to canvas when you call getImageData which results in a blank byte array.