创建并填充3D数组JavaScript

时间:2018-11-23 08:51:25

标签: javascript arrays 3d

我试图用“ rgb(255,48,144)”填充3d数组(16x16x16),然后通过在数组中找到它来绘制带有该颜色的Rect(arr [15] [3] [9] )。

这是到目前为止我得到的:

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>

1 个答案:

答案 0 :(得分:1)

我认为您不适当地初始化了3维数组。以下是您要尝试执行的操作吗?

此外,它是fillStyle而不是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> Fargekube </title>
</head>


<body>

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