virtual canvas putimagedata not working

青春壹個敷衍的年華 提交于 2019-12-02 18:58:20

问题


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:


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.



来源:https://stackoverflow.com/questions/23781356/virtual-canvas-putimagedata-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!