我一直在用 javascript 开发一个画布应用程序,我需要在其中定义一个 9 单元格网格(3x3),并且在每个网格中都有一个画布元素。
问题是,我已经有一个名为 grid 的数组,其中包含表示每个单元格大小的数据。
var grid = new Array();
grid[0] = {x:[0, elemWidth], y:[0, elemHeight]};
grid[1] = {x:[elemWidth, elemWidth*2], y:[0, elemHeight]};
grid[2] = {x:[(elemWidth*2), sWidth], y:[0, elemHeight]};
grid[3] = {x:[0, elemWidth], y:[elemHeight+1,elemHeight*2]};
grid[4] = {x:[elemWidth, elemWidth*2], y:[elemHeight, elemHeight*2]};
grid[5] = {x:[(elemWidth*2), sWidth], y:[elemHeight, elemHeight*2]};
grid[6] = {x:[0, elemWidth], y:[(elemHeight*2), sHeight]};
grid[7] = {x:[elemWidth, elemWidth*2], y:[(elemHeight*2), sHeight]};
grid[8] = {x:[(elemWidth*2), sWidth], y:[(elemHeight*2), sHeight]};
这会在 Chrome Inspector 上产生以下输出:
据我所知,我应该能够使用以下代码获得 x 和 y 值
canvas[i].fillRect(grid[i].x[0], grid[i].y[0], grid[i].x[1], grid[i].y[1]);
canvas[i].strokeRect(grid[i].x[0], grid[i].y[0], grid[i].x[1], grid[i].y[1]);
每个都应该给我相应的值。
我不明白为什么我可以在打开时一切正常canvas[0]
(一切都在浏览器上呈现)但是当涉及到后续canvas[i]
(i>0)时不会呈现并且我得到一个未定义的值,尽管 HTML 生成标签每个画布元素。
我在声明数组时做错了什么吗?
编辑
为了简单和可读性,对代码进行了一些更改:
function createCanvas() {
/* criar grelha aqui */
var sWidth = window.innerWidth; //- 50;
var sHeight = window.innerHeight; //- 50;
var elemWidth = sWidth / 3;
var elemHeight = sHeight / 3;
var grid = new Array();
var row1 = [0, elemHeight];
var row2 = [elemHeight, elemHeight*2];
var row3 = [elemHeight*2, sHeight];
var col1 = [0, elemWidth];
var col2 = [elemWidth, elemWidth*2];
var col3 = [elemWidth*2, sWidth];
grid[0] = [col1, row1];
grid[1] = [col2, row1];
grid[2] = [col3, row1];
grid[3] = [col1, row2];
grid[4] = [col2, row2];
grid[5] = [col3, row2];
grid[6] = [col1, row3];
grid[7] = [col2, row3];
grid[8] = [col3, row3];
for (var i = 0; i < grid.length; i++) {
var c = document.getElementById('content');
var newCanvas = document.createElement('canvas');
newCanvas.setAttribute('id', 'canvas'+i);
c.appendChild(newCanvas);
canvas[i] = new Canvas('canvas'+i, 0, function() {});
canvas[i].clear();
canvas[i].setAutoResize(true);
canvas[i].canvasElement.width = elemWidth - 2;
canvas[i].canvasElement.height = elemHeight - 2;
canvas[i].fillStyle('#000000');
canvas[i].strokeStyle('#FFFFFF');
canvas[i].fillRect(grid[i][0], grid[i][0], grid[i][2], grid[i][3]);
canvas[i].strokeRect(grid[i][0], grid[i][0], grid[i][4], grid[i][5]);
这段代码比之前的版本完整多了
与此同时,我设法让 3 个单元格进行渲染(虽然 3 个单元格,应该是 1x3 实际上是 2x1,因为不知何故渲染没有正确发生,我认为这可能是一个 CSS 问题)
编辑2
我再次对上面的代码进行了一些更改。以及网格阵列扩展视图的新屏幕截图。