Canvas How to - Draw objects in grid








Question

We would like to know how to draw objects in grid.

Answer


<!--from w  w  w.ja va 2s  . c  om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var canvas = document.getElementById('canvas');
    canvas.width = 400;
    canvas.height = 400;
    var context = canvas.getContext('2d');
    // setup a basic squares to use for our example
    var object1 = {
        x: 0,
        y: 0,
        width: 25,
        height: 25,
        color: "green"
    };
    // varibales that track the values of our grid
    var startX = 10;
    var startY = 10;
    var row = 0;
    var maxColumns = 10;
    var total = 50;
    var padding = 5;
    // horizontal layout
    for (var i = 0; i < total; i++) {
        var column = i % maxColumns;
        var newX = (column * (object1.width + padding)) + startX;
        var newY = (row * (object1.height + padding)) + startY;
        context.fillStyle = object1.color;
        context.fillRect(newX, newY, object1.width, object1.height);
        if (column == (maxColumns - 1)) {
            row++;
        }
    }
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: