Creating an Array of Images with the JavaScript Canvas Element

As I dive into learning JavaScript and experimenting without jQuery, I am interested in creating something similar to this example. However, my goal is to utilize an array of images instead of just one.

This is how my image array is structured:

var image_array = new Array();
image_array[0] = "image1.jpg"; 
image_array[1] = "image2.jpg";

The canvas element setup is as follows (largely inspired by the Mozilla site):

function draw() {
      var ctx = document.getElementById('canvas').getContext('2d');
      var img = new Image();
      img.src = 'sample.png';
      img.onload = function(){
        for (i=0; i<5; i++){
          for (j=0; j<9; j++){
            ctx.drawImage(img, j*126, i*126, 126, 126);
          }
        }
      }
    }

The code currently uses the image "sample.png," but I aim to modify it to display images from the array. Specifically, displaying a different one each time it loops.

I apologize if the explanation is unclear.

Answer №1

To position the images, simply iterate through the array and use the width and height properties:

function draw() {  
  var ctx = document.getElementById('canvas').getContext('2d'),  
      img, i, image_array = [];  

  image_array.push("http://sstatic.net/so/img/logo.png");   
  image_array.push("http://www.google.com/intl/en_ALL/images/logo.gif");  
  // ...  

  for (i = 0; i < image_array.length; i++) {  
    img = new Image();  
    img.src = image_array[i];  
    img.onload = (function(img, i){ // temporary closure to store loop 
      return function () {          // variables reference 
        ctx.drawImage(img,i*img.width,i*img.height);  
      }  
    })(img, i);  
  }  
}  

See this example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Injecting script into a webpage and initiating an ajax request prior to receiving a response

Trying to accomplish something a bit complex that I believe is feasible, or perhaps someone could offer a suggestion on how to achieve it. At website A, there is a database containing booking data. At website B, the goal is to display information about w ...

What is the best approach for updating data in a v-data-table dynamically?

I'm currently working on a node and electron application that utilizes vuetify to create a table (v-data-table) fetching data from an oracle database. The issue I'm facing is that even though the data changes based on the input value, the table f ...

Issue with Bootstrap 5 Dropdown not toggling back

<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Creative Admin Panel</title> <link rel="stylesheet" href=&q ...

How can I receive the response from a GET request using React Query? I am currently only able to get the response

I have created a search component where I input a name in the request, receive a response, and display it immediately. However, after the first input submit, I get undefined in response. Only after the second submit do I get the desired response. The tec ...

Sending a parameter to a JavaScript function on a separate page

My current setup involves an aspx page featuring a drop down list. Once a selection is made, I am required to transmit the chosen value to a separate javascript function located within another page. This second page is dedicated to showcasing a map using ...

Storing the outcome of a promise for Node.js MSSQL validation is crucial

let FetchDataFromDatabase=(query) =>{ { let sql=require('mssql'); let configuration={ server:'127.0.0.1', database:'TestDB', user:'user', password:'user', }; ...

Run JavaScript code to retrieve the console log using Selenium WebDriver or WatiN

(Apologies for the detailed explanation) I am looking to ensure a page loads entirely before proceeding, but it seems browsers have varied responses when attempting to use readyState or onLoad. In the application I am currently developing, a specific l ...

Issues with loading Ruby on Rails 4.0 and JavaScript in combination

I am facing an issue with my JavaScript file named "front.js" that I load from "application.js" using the usual code: //= require front Within "front.js", there are several functions that I want to trigger when the document is ready, like this: $(docume ...

Loading multiple Meteor templates is a breeze with the ability to hide data

I have implemented a selection box where users can choose which inputs are relevant to them. The goal is to dynamically load only the input fields that the user has selected, hiding those that are irrelevant. However, I feel that my current approach is clu ...

Guide to importing images (.svg, .png) into a React component

I'm currently facing an issue trying to upload an image file in one of my React components using webpack. My project is already set up with web pack. Below is the code snippet for the component: import Diamond from '../../assets/linux_logo.jpg& ...

Looping animations using AngularJS

I have implemented a custom directive to trigger an animation on an element when a specific field is empty on the page. However, I am facing an issue where the animation only works once when the user clicks the button with the directive. Subsequent clicks ...

The time complexity comparison between one-dimensional and two-dimensional arrays

Consider the scenario where we are taking input from the user for a one-dimensional array of size n, resulting in a time complexity of O(n). for(i=0;i<n;i=i+1) { scanf("%d",&a[i]); } If we expand this to a two-dimensional array, ...

Querying a Database to Toggle a Boolean Value with Jquery, Ajax, and Laravel 5.4

I am facing an issue with a button I created to approve a row in a table. It seems that everything is working fine when clicking the button, but there is no change happening in the MySQL database Boolean column. Here is the code for my button: <td> ...

What is the best way to implement a day timer feature using JavaScript?

I am looking for a timer that can automatically change the rows in an HTML table every day. For example, if it is Day 11, 12, or 25 and the month is February at 8 AM, the rows should display "Hello!". function time() { var xdate = new Date(); var ...

Leveraging the outcome of a for loop in order to set a condition within an else if statement

How can I condition my third else if statement based on the result of a for loop? //If player clicks centre on first move go in corner square if (current[4] === playerToken && this.state.stepNumber === 1) { let move = c ...

fullpage.js separate segments

Currently utilizing fullpage.js library from this source The structure I have implemented looks like the following <section id="portfolio"> <div class="col-lg-5 col-sm-5" id="portfolio-left"> &nbsp; </div> <d ...

What is the best technique for accessing information from protractor's promises series?

My function successfully retrieves the index of an element with the text "check" and prints it using console.log: function getIndex() { return element.all(by.css(".palette__item.ng-scope>span")).then(function (colorList) { colorList.forEach ...

How can you find the index of an HTML element while excluding any clearfix divs?

In the process of developing a CMS, I find myself in need of determining the index of the element I am currently working on. Consider the following stripped-down HTML structure: <div class="row"> <article class="col-md-4 col-sm-4 project" &g ...

JavaScript alert system

Seeking advice on a situation. Here's the scenario I'm facing: In a messaging platform, I have an array of users who are currently online. When a new user joins the chat, I want to notify the first user in the array. If there's no response w ...

Achieving consistent scroll position when utilizing the history.js library to navigate back with the click of a button

I need help implementing a feature that allows users to return to the same position on a webpage when clicking the back button. A common example is on ecommerce sites where if you scroll down, click on a product, then go back, you should be taken back to t ...