Pass Multiple Image References to a User Defined Function in JavaScript

← PrevNext →

A User Defined Function in JavaScript, allows us to perform a task multiple times without having to rewrite the codes repeatedly. You can pass values to the function and here I’ll show you how to pass multiple image references to a User Defined Function in JavaScript without using an Array.

Let us assume I have multiple images on my web page. Each image is defined using the <img /> tag. I’ll extract all the images on my web page and pass the reference of each image to my User Defined Function (UDF), called myCanvas().

Also Read: Two Simple Methods to Add Images to HTML5 Canvas using JavaScript

You can use the image references for various purposes. In my example here, I’ll use the references to draw the images on dynamically created canvas elements. Since I have multiple images, I’ll have to create a canvas each dynamically for all the images.

The Markup

In the markup section, I have 3 images using <img /> tag. Each has a unique id.

When the page loads, I’ll extract all the images on the page using a loop and pass the reference of each image to a User Defined Function and draw the images on dynamically created HTML5 canvas elements.

<html>
<body>
    <p>Images inside a DIV are passed to a User Defined Function (or UDF) in JavaScript and reused.</p>
    <div style="border:solid 1px #CCC;padding:10px;width:auto;">
        <img src="../../images/theme/angularjs.png" width="64px" id="angular" />
        <img src="../../images/theme/javascript.png" width="64px" id="javascript" />
        <img src="../../images/theme/autocomplete.png" width="64px" id="autocomplete" />
    </div>
    
    <br />
</body>

<script>
    window.onload = function () {
        // Get all the images on the web page.
        for (i = 0; i <= document.images.length; i++) {
            var image = document.getElementById(document.images[i].id);
            myCanvas(image);         // Call a function with the image reference.
        }

        // The User Define Function (or UDF), which takes image references as parameter.
        function myCanvas(img) {
            var canvas = document.createElement('canvas');      // Create a Canvas.
            var ctx = canvas.getContext('2d');                  // Create Canvas context.

            ctx.drawImage(img, 0, 0, 70, 70);    // Draw the image to the Canvas.

            document.body.appendChild(canvas);
        }
    }
</script>
</html>
Try it

I am not using an Array as parameter. I am simply calling the function repeatedly inside the for loop and passing the reference of each image.

Also Read: 3 ways to find the File Extension using JavaScript and jQuery

Well, that's it. Happy Coding. 🙂

← PreviousNext →