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.

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.

    <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" />
    <br />

    window.onload = function () {
        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.

        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.

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

Previous - How to Replace a String with another String in the URL Bar using JavaScriptNext - Check if the Element is an Image using JavaScript tagName Property

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 Google+

Related Posts:

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