2014-01-14 156 views
0

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

+0

哪个网格你在说什么?请指定您正在使用的框架或提供任何其他提示。否则,我们可以猜测... – gehho

+0

将宽度和高度除以该方向上的单元格数量? – Teepeemm

回答

0

这里是@ 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> 
+0

这真棒!所以..如果画布尺寸不是一个完美的300x300?如果它像300x250那么怎么办? – spez86

+1

没关系,把它用在上面的小提琴上:http://jsfiddle.net/yv0deead/2/ – spez86