Adding grid over Fabric.js canvas

High schooler picture High schooler · Jun 23, 2013 · Viewed 11.9k times · Source

I just started using Fabric.js (I have to say, I'm impressed).

I want to add a grid over the fabric objects. In the following code, I am putting my grid canvas right over on the Fabric canvas. The problem here is that, I now cannot move my fabric objects!

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  <script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
  <script type='text/javascript' src='http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.2.0/fabric.all.min.js'></script>

</head>
<body>

<div style="height:480px;width:640px;border:1px solid #ccc;position:relative;font:16px/26px Georgia, Garamond, Serif;overflow:auto;">

 <canvas id="rubber" width="800" height="800" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
 <canvas id="myCanvas" width="800" height="800" 
   style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

<script>
//<![CDATA[ 
$(window).load(function(){
$(document).ready(function () {

    function renderGrid(x_size,y_size, color)
    {
        var canvas = $("#myCanvas").get(0);
        var context = canvas.getContext("2d");

        context.save();
        context.lineWidth = 0.5;
        context.strokeStyle = color;

        // horizontal grid lines
        for(var i = 0; i <= canvas.height; i = i + x_size)
        {
            context.beginPath();
            context.moveTo(0, i);
            context.lineTo(canvas.width, i);
            context.closePath();
            context.stroke();
        }

        // vertical grid lines
        for(var j = 0; j <= canvas.width; j = j + y_size)
        {
            context.beginPath();
            context.moveTo(j, 0);
            context.lineTo(j, canvas.height);
            context.closePath();
            context.stroke();
        }

        context.restore();
    }

    renderGrid(10,15, "gray");
});

});//]]>  

  var canvas = new fabric.Canvas('rubber');
  canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));

  canvas.selectionColor = 'rgba(0,255,0,0.3)';
  canvas.selectionBorderColor = 'red';
  canvas.selectionLineWidth = 5;
</script>


</body>
</html>

I am hoping that there is a way to do this in Fabric itself.

Any help would be awesome, thanks!

Answer

John picture John · Nov 26, 2013

This two lines of code will work:

var gridsize = 5;
for(var x=1;x<(canvas.width/gridsize);x++)
                        {
                            canvas.add(new fabric.Line([100*x, 0, 100*x, 600],{ stroke: "#000000", strokeWidth: 1, selectable:false, strokeDashArray: [5, 5]}));
                            canvas.add(new fabric.Line([0, 100*x, 600, 100*x],{ stroke: "#000000", strokeWidth: 1, selectable:false, strokeDashArray: [5, 5]}));
                    }