在画布中绘制一个简单的网格?

时间:2012-04-23 23:30:20

标签: java swing canvas grid awt

我用Java编写了Conway的生命游戏,我想在浏览器中显示它。我想学习一些Canvas,那么绘制2D网格并用颜色填充每个单元格的首选方法是什么?感谢。

1 个答案:

答案 0 :(得分:0)

这将构成一个网格。我认为能够定位或确定元素或其他东西的坐标以及其他一些可能的方便用例是有用的。

var grid = function() {
    for (var i = 0; i < canvasWidth || i < canvasHeight; i += 100) { // 100 represents the width in pixels between each line of the grid
        // draw horizontal lines
        ctx.moveTo(i, 0);
        ctx.lineTo(i, canvasHeight);
        // draw vertical lines
        ctx.moveTo(0, i);
        ctx.lineTo(canvasWidth, i);
    }
    ctx.save();
        ctx.strokeStyle = 'hsla(200, 0%, 20%, 0.8)';
        ctx.stroke();
    ctx.restore();
};

// Call the function
grid()

希望这会有所帮助,也是你正在尝试做的事情。 :)

编辑:如果你想用不同的颜色填充每个网格方块,那么这个函数将不起作用,或者至少可以与另一个以与函数类似的方式创建和填充方块的函数组合使用以上,但根据画布宽度和高度的尺寸切割宽度和高度。

相关问题