javascripthtmldrawimage

Javascript's function drawImage() needs the page to reload to work


I have a problem with the javascript function drawImage(). It needs the page to reload to work. My code:

<canvas id="canva" width="350px" height="350px" style="opacity: 1;"></canvas>    
<script>            
var monImage = new Image();
monImage.src = "myPicture";
monImage.onload = action();

function action() {
  var canvas = document.getElementById("canva");
  var context = canvas.getContext('2d');
  context.drawImage(monImage,20,20,canvas.clientWidth-40,canvas.clientHeight-40);
  var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
  context.putImageData(imageData, 0, 0);
}
</script>```


I tried waiting for the image to load but that didn't work either.

Solution

  • Try monImage.onload = action instead of monImage.onload = action()