如何创建动态网格

时间:2014-01-14 15:47:21

标签: javascript css math canvas grid

我正在尝试使用动态宽度和高度创建网格。确保每个单元区域宽度和高度相等的公式是什么?

1 个答案:

答案 0 :(得分:1)

这是@ Teepemm的想法付诸代码。

如果您希望所有宽度与其他宽度相同,并且所有高度都与其他高度相同:

var xSpan=cw/lineCount;
var ySpan=cw/lineCount;

如果你想要方形单元格(宽度==高度),那么只需使用1个跨度。注意:在这种情况下,底行的单元格可能不是正方形:

var span=cw/lineCount;

这是代码和演示:http://jsfiddle.net/m1erickson/8MTkv/

<!doctype html>
<html lang="en">
<head>

  <style>
      body{ background-color: ivory; }
      #wrapper{ position:relative; }
      canvas{ position:absolute; left:40px; top:5px; border:1px solid red;}
      #amount{ position:absolute; left:1px; top:5px; margin-bottom:15px; width:23px; border:0; color:#f6931f; font-weight:bold; }
      #slider-vertical{ position:absolute; left:5px; top:40px; width:15px; height:225px; border:0px; color:#f6931f; font-weight:bold; }
  </style>

  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

  <script>

  $(function() {

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;

    var $amount=$("#amount");

    $( "#slider-vertical" ).slider({
      orientation: "vertical",
      range: "min",
      min: 2,
      max: 30,
      value: 10,
      slide: function( event, ui ) {
        var value=ui.value;
        $amount.val(value);
        drawGrid(value);
      }
    });

    $amount.val( $( "#slider-vertical" ).slider( "value" ) );
    drawGrid(10);


    function drawGrid(lineCount){
        var xSpan=cw/lineCount;
        var ySpan=cw/lineCount;
        ctx.clearRect(0,0,cw,ch);
        ctx.save();
        if(lineCount/2===parseInt(lineCount/2)){
            ctx.translate(.5,.5);
        }
        ctx.beginPath();
        for(var i=0;i<lineCount;i++){
            var x=(i+1)*xSpan;
            var y=(i+1)*ySpan;
            ctx.moveTo(x,0);
            ctx.lineTo(x,ch);
            ctx.moveTo(0,y);
            ctx.lineTo(ch,y);
        }
        ctx.lineWidth=0.50;
        ctx.stroke();
        ctx.restore();
    }

  });   // end $(function(){});

  </script>
</head>
<body>
    <div id="wrapper">
        <input type="text" id="amount" />
        <div id="slider-vertical"></div>
        <canvas id="canvas" width=300 height=300></canvas>
    </div>
</body>
</html>