Passing parameter to a function

Hi,
How can I pass a parameter to the function here? This script draws an image on the canvas. I would like to control the position of the image on the canvas using the paramater.

<canvas id="drawing" width="800" height="800"></canvas>
      <script>
                var canvas = document.getElementById("drawing");
                var ctx = canvas.getContext("2d");
                 var canvas = document.getElementById('drawing');
                 var context = canvas.getContext('2d');
                  var imageObj = new Image();
                  imageObj.onload = function(x) {
                context.drawImage(imageObj, x, 40, 100, 100);
                  };
                  imageObj.src = 'rocket.jpg';
        </script>

I can do this in a simpler situation but not for this function i.e.

                  var fun = function(y){
                      console.log(y);
                  }
                  fun("tester");

Thanks

This function will be called by browser automatically when image is loaded, so how will browser know what it should pass as value of your parameter?

Sure, you can do this when you execute function by yourself. In that case you know what parameters you should pass to it,

Actually, it seems like you want global variable here.

var x = 100;
imageObj.onload = function() {
    context.drawImage(this, x, 40, 100, 100);
};
1 Like

Yes I see your point. I actually want to have the image move to a certain position when a button is clicked. I was just trying to control the position for now using a parameter. I won’t be using onload.
Thanks very much for you help. :+1:

Here’s a tutorial on canvas animation, that I’ve found has helped quite a few people.

1 Like

Fantastic examples on that MDN link.
Thank you for these

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.