Canvas How to - Draw grid








Question

We would like to know how to draw grid.

Answer


<!--   w  ww  .j a  v a 2s. c  om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='https://ajax.googleapis.com/ajax/libs/mootools/1.4.1/mootools.js'></script>
</head>
<body>
<canvas id="c" width="300" height="225"></canvas>
<script>
function draw_grid() {
    var c_canvas = document.getElementById("c");
    var context = c_canvas.getContext("2d");
    for (var x = 0.5; x < 500; x += 10) {
        context.moveTo(x, 0);
        context.lineTo(x, 375);
    }
    for (var y = 0.5; y < 375; y += 10) {
        context.moveTo(0, y);
        context.lineTo(500, y);
    }
    context.strokeStyle = "#eee";
    context.stroke();
}
draw_grid();
</script>
</body>
</html>

The code above is rendered as follows: