2017-04-06 82 views
0

我一直在试图创建一个显示11x11矩阵的画布。在画布上显示11x11矩阵

const canvas = document.getElementById('canvasGame'); 
const context = canvas.getContext('2d'); 

context.scale(10, 10); 

context.fillstyle = '#000'; 
context.fillstyle(0,0, canvas.width, canvas.height); 


const matrix = [ 
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 
]; 

根据矩阵内部的数字,它将创建一个特定颜色的矩形。
我已经创建了一个基本的函数,通过每个条目。

if = 0,白色矩形。
其他,黑色矩形。

function drawMatrix(matrix){ 
    matrix.forEach((row, y) =>{ 
     row.forEach((value, x) => { 
      if(value === 0) { 
       context.fillStyle = 'white'; 
       context.fillRect(x, y, 1, 1); 
      } 
      else 
      { 
       context.fillStyle = 'black'; 
       context.fillRect(x, y, 1, 1); 
      } 
     }); 
    }); 
} 

drawMatrix(matrix); 

然而,当我打开我的html文件,我的.js文件和我的画布建立它不离开我已经应用到我的画布造型加载任何东西。

Screenshot: What it loads.

我的HTML,如果该事项。

<html> 
<head> 
    <title>Testing Grounds</title> 
    <style> 
     body { 
     background: #345; 
     color: #fff; 
     font-family: sans-serif; 
     font-size: 2em; 
     text-align: center; 
     } 
     canvas { 
     border: dashed .2em #fff; 
     height: 90vh; 
     } 
    </style> 
</head> 
<body> 
    <h1>Test Zone</h1> 
    <p>Using a canvas to display 11x11 matrix</p> 
    <canvas id="canvasGame" width="350" height="350"/> 
    <script src="app.js"></script> 
</body> 
</html> 

回答

0

您正在创建的矩形是1 x 1像素,并始终位于左上角。你应该计算矩形的宽度/高度(宽度/ 11,高度/ 11)。然后使用这些值转换x和宽度。像下面的东西应该工作:

function drawMatrix(matrix){ 
    var cellWidth = canvas.width/11.0; 
    var cellHeight = vanvas.height/11.0; 

    matrix.forEach((row, y) =>{ 
     row.forEach((value, x) => { 
      context.fillStyle = cellColor(value); 
      context.fillRect(x * cellWidth, y * cellHeight, cellWidth, cellHeight); 
     }); 
    }); 
} 
function cellColor(val) { 
    if(value == 0) 
    { 
     return 'white'; 
    } 

    return 'black'; 
} 

drawMatrix(matrix); 

这将通过每个元素计算的宽度和细胞的高度的环,并用白色或黑色根据值绘制矩形。

您还应该确保drawMatrix函数在主体加载后调用。

+0

使用您提供的代码我仍然只有我的画布出现,没有别的。 [链接](https://gyazo.com/922a1fdcf4a1bcb59562988fcddd3458)<。我的JS的截图。 – AchillesDH