Search code examples
htmlcanvashtml5-canvas

Draw a grid on an HTML 5 canvas element


I've been searching everywhere and couldn't find how to draw a grid on an HTML5 Canvas. I'm new to HTML5 and canvas.

I know how to draw shapes but this drawing grid is taking forever to understand.

Can someone help me on this?


Solution

  • The answer is taken from here Grid drawn using a <canvas> element looking stretched

    Just edited it a little, hope it helps

    // Box width
    var bw = 400;
    // Box height
    var bh = 400;
    // Padding
    var p = 10;
    
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    function drawBoard(){
        for (var x = 0; x <= bw; x += 40) {
            context.moveTo(0.5 + x + p, p);
            context.lineTo(0.5 + x + p, bh + p);
        }
    
        for (var x = 0; x <= bh; x += 40) {
            context.moveTo(p, 0.5 + x + p);
            context.lineTo(bw + p, 0.5 + x + p);
        }
        context.strokeStyle = "black";
        context.stroke();
    }
    
    drawBoard();
    body {
        background: lightblue;
    }
    #canvas {
        background: #fff;
        margin: 20px;
    }
    <div>
        <canvas id="canvas" width="420px" height="420px"></canvas>
    </div>