Canvas How to - Draw grid lines








Question

We would like to know how to draw grid lines.

Answer


<!--  w  ww. ja v  a 2 s  .  c o m-->
<!DOCTYPE html>
<html>
<body>
  <canvas id="myCanvas" width="400" height="400"></canvas>
  <script type='text/javascript'>//<![CDATA[ 
window.onload = function() {
    var objCanvas = document.getElementById("myCanvas");
    var objContext = objCanvas.getContext("2d");
    var intGridWidth = 20;
    function drawBackground() {
        objContext.clearRect(0, 0, objCanvas.width, objCanvas.height);
        // Draw the black background
        objContext.fillStyle = 'black';
        objContext.fillRect(0, 0, objCanvas.width, objCanvas.height);
        objContext.strokeStyle = "white";
        objContext.lineWidth = 2;
        // Vertical lines
        var i, l = Math.round(objCanvas.width / intGridWidth);
        for (i = 1; i < l; i++) {
            objContext.moveTo(i * intGridWidth, 0);
            objContext.lineTo(i * intGridWidth, objCanvas.height);
            objContext.stroke();
        }
        // Horizontal lines
        var i, l = Math.round(objCanvas.height / intGridWidth);
        for (var i = 1; i < l; i++) {
            objContext.moveTo(0, i * intGridWidth);
            objContext.lineTo(objCanvas.width, i * intGridWidth);
            objContext.stroke();
        }
    }
    drawBackground();
};
</script>
</body>
</html>

The code above is rendered as follows: