1

What i want to do is to draw an image that I have saved locally onto a canvas. I then want to convert that canvas to a png image. The image loads on the canvas but the png image that I create is blank. Does anyone know how to fix this?

<!DOCTYPE html>
<html>
 <head>

 </head>
 <body>
  <img src="" id="canvasImage" />
  <canvas id="canvasId" width="160" height="145"></canvas>
  
  <script>
   
   var canvas = document.getElementById('canvasId');
   var context = canvas.getContext("2d");
   
   image = new Image();
   image.src = "images/rightarrow.png";
   image.onload = function(){
    context.drawImage(image, 0, 0);
   }
   
   var imgTag = canvas.toDataURL("image/png");
   document.getElementById("canvasImage").src = imgTag;
  
  </script>
  
 </body>
</html>

1 Answers1

1

You need to create your image inside onload handler

        image = new Image();
        image.src = "images/rightarrow.png";
        image.onload = function(){
            context.drawImage(image, 0, 0);
            var imgTag = canvas.toDataURL("image/png");
            document.getElementById("canvasImage").src = imgTag;
        }
Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50
  • Awesome thanks. It now creates the png image but it has dissapeared on the canvas now hehe. Is there any way to get it back onto the canvas? – Dominic Oryema Nov 27 '14 at 20:56
  • @DominicOryema hm, that's really strange, can you check this post: http://stackoverflow.com/questions/26783586/canvas-todataurl-returns-blank-image-only-in-firefox may be it applies to you – Vsevolod Goloviznin Nov 27 '14 at 20:58
  • after moving everything in ``img.onload`` I am getting error about *cross-origin data* – Hidayt Rahman Nov 20 '18 at 09:39