Pass Multiple Image References to a User Defined Function in JavaScript

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.

<html>
<body>
    <img src="image1.png" id="angular" />
    <img src="image2.png" id="javascript" />
    <img src="image3.png" id="auto" />
    
    <br />
</body>
The Script

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.

<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 THE FUNCTION WITH THE IMAGE REFERENCE.
        }

        // MY USER DEFINED FUNCTION, WHICH TAKES IMAGE REFERENCES AS PARAMETER.
        function myCanvas(img) {

            // CREATE A CANVAS.
            var canvas = document.createElement('canvas');

            // CREATE CANVAS CONTEXT.
            var ctx = canvas.getContext('2d');

            canvas.width = img.width;
            canvas.height = img.height;

            ctx.drawImage(img, 0, 0);           // DRAW THE IMAGE TO THE CANVAS.

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

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. Hope you find this example useful.

Related Posts:

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+
comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!