How to make a 3D array in JavaScript and populate it

I am attempting to populate a 3D array with dimensions of 16x16x16, all filled with the color "rgb(255, 48, 144)". My goal is then to draw a rectangle using this color by referencing its position in the array ( arr[15][3][9] ).

Here is my progress so far:

var ctx = document.getElementById("canvas").getContext("2d");
var canvas = document.getElementById("canvas");

var arr = new Array(16);
for(var i = 0; i < arr.length; i++){

    arr[i] = new Array(16);

    for(var j = 0; j < arr[i].length; j++){


        arr[i][j] = "rgb(255, 48, 144)";

        for(var k = 0; k < arr[i][j].length; k++){
            arr[i][j][k] = "rgb(255, 48, 144)";
        }

    }
}
ctx.fillstyle = arr[15][3][9];
ctx.fillRect(0, 0, 100, 100);
<!doctype HTML>
<html>

<head>
    <meta charset="UTF-8">
    <title> Fargekube </title>
</head>


<body>

    <canvas id="canvas" width="200" height="200></canvas>
    
</body>
</html>

Answer №1

It seems like you may have initialized your 3-dimensional array incorrectly. Here's the corrected code:

Also, make sure to use fillStyle instead of fillstyle

var ctx = document.getElementById('canvas').getContext('2d');
var canvas = document.getElementById('canvas');

var dimensionSize = 16;

var arr = [];

for (var i = 0; i < dimensionSize; i += 1) {
  arr[i] = [];
  
  for (var j = 0; j < dimensionSize; j += 1) {
    arr[i][j] = [];
    
    for (var k = 0; k < dimensionSize; k += 1) {
      arr[i][j][k] = 'rgb(255, 48, 144)';
    }
  }
}

console.log(arr[15][3][9]);

ctx.fillStyle = arr[15][3][9];
ctx.fillRect(0, 0, 100, 100);
<!doctype HTML>
<html>

<head>
    <meta charset="UTF-8">
    <title> Color Cube </title>
</head>


<body>

    <canvas id="canvas" width="200" height="200"></canvas>
    
</body>
</html>

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

The value of React state may be unpredictable, even if it appears to be defined on the

<li className="field-title">Role: </li> {console.log(this.state.userData.roles)} {this.state.userData.roles.map((role) => { return ( <li>{role.name}</li> ) })} Even though when I console log the state ...

Using Vuejs to iterate over nested data

I am looking to implement a nested v-for loop in Vuejs, but I am unsure about how to structure my Data and the v-for loop itself. My goal is to iterate through modifiers without having to specify modifiers1, modifiers2 individually. The idea is to have t ...

Placing an image onto a THREE.js plane

Whenever I attempt to place a .png image on my plane, it simply vanishes. Could it be that THREE.js isn't compatible with Vue.js? Is there another 3D library that supports Vue.js? I'm also interested in adding an SVG, but I haven't quite f ...

Different Array Combinations

There are two 1D arrays, X and Y, representing coordinates. For example: X = [1,2,3], Y = [a,b,c] I want to combine each value of X with every value of Y in a two-column array: For instance: XY = [1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c] Note that this is n ...

Seamless side-to-side navigation

Currently, I am working on a website that has horizontal overflow instead of the common vertical scroll. While everything seems to be functioning properly, I need to enhance the user experience by adjusting the amount scrolled to move larger sections of th ...

Storing Iframe content without the need for a "save button" in a colorbox

I'm currently working on a small project that involves a main HTML page and a separate settings.html file. I've set it up so that the settings page pops up when clicked, using the following code: jQuery('#settings').colorbox({iframe:tr ...

Having trouble integrating a custom dialog with DirtyForms plugin

I have successfully implemented DirtyForms, a plugin that triggers a confirmation dialog when a user tries to navigate away from a page. The base functionality of the plugin is working as intended. Now, I am trying to integrate jQuery UI's Dialog for ...

Mastering React Final Form: Displaying data using a button placed outside the form

I have a query regarding integrating my form component (<InvoiceForm.tsx />) with a button component (<Button.js />) to save its data in the database. The button component is located in another component called <InvoiceList.tsx />, which ...

There seems to be an issue preventing the Chrome browser from launching with the error message: "ERROR: connect ECONNREFUSED 127.0

My setup includes: Operating System: Windows 10 (64 bit) Browser: Chrome version 58 Node.js: 6.10.1 Npm: 3.10.10 Chromedriver: 2.29.0 After running my tests with Chrome using Selenium standalone, I encountered an error in the console where Selenium was ...

Issue with the demo code for Vue Stripe Checkout

As I delve into the world of Vue-Stripe-Checkout, I encountered a snag right from the start with the demo code provided. The issue arises when utilizing the Vue Stripe Elements component. Has anyone else experienced this problem? There are no errors displa ...

Guide on obtaining a refined array result within a document using a mongoose query

I require assistance in creating a query that retrieves specific documents within an array of a main document. The collection stored in the database is as follows: { "_id": "5ed49b42d6fc0c3878c875a2", "stockID": "Stock-1", ...

Iterating recursively through a tree structure to update properties using Mongoose

I have a unique structure resembling a tree that I've set up to store comments. Each "comment" acts as a node with a "parent" property linking it to another "comment" node. Additionally, I've included a "replyCount" field on each node to keep tra ...

Get the png image file and display a preview of it

Within my template, I have an img tag that is linked to a state known as "imageBuffer" <img v-bind:src="imageBuffer" alt="" /> In the logic of the page, there are two file inputs and I've utilized a single function to manag ...

In what scenarios would it be more beneficial to utilize a vector over an array?

I'm a little confused about the scenarios where vectors would be more beneficial than arrays. Can someone provide me with an example of when choosing a vector over an array is the better option? Thanks! ...

In Node.js, use the `[]` operator to select elements from an array of strings without including

In my situation, I am working with an array of strings which can sometimes be an array containing only one string. The issue is that when this happens, using array[0] to retrieve the value does not return the entire string but rather just the first charact ...

Having trouble with Node.js multiparty upload functionality

I'm facing an issue with the functionality of multiparty.Form(). Specifically, I am attempting to print numbers like 2, 3, and 4. Below is the code snippet for uploading images: app.post('/gallery/add',function(req, res,next) { var input = ...

Converting lengthy timestamp for year extraction in TypeScript

I am facing a challenge with extracting the year from a date of birth value stored as a long in an object retrieved from the backend. I am using Angular 4 (TypeScript) for the frontend and I would like to convert this long value into a Date object in order ...

Tips on passing string without double quotes within a MongoDB query

When trying to pass a string to my mongodb query, I encountered an issue where double quotes were added to the string once inside the query. The criteria is being passed as a string because it is dynamically formed that way: str1={AccId:8,WSId:24237,Case ...

Only allowing designated email addresses to authenticate using Gmail Oauth

Is there a way I can limit logins by doing the following? I'm facing an issue where the page keeps reloading constantly after logging in once. function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log('Name: ...

What is the best way to calculate the average of two particular keys in an array using PHP, without averaging all the values in the array?

I am a beginner in php, sql, and related languages and I am attempting to develop a basic member system to track scores and calculate specific averages. However, I am facing issues with getting the correct output. Controller: <?php $reco ...