【问题标题】:How to create dynamic grid如何创建动态网格
【发布时间】:2014-01-15 15:54:06
【问题描述】:

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

【问题讨论】:

  • 你说的是哪个网格?请指定您正在使用的框架或提供任何其他提示。否则我们只能猜测......
  • 将宽度和高度除以该方向的单元格数?

标签: javascript css math canvas grid


【解决方案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>

【讨论】:

  • 这太棒了!那么.. 如果画布尺寸不是完美的 300x300 怎么办?如果是 300x250 之类的呢?
猜你喜欢
  • 2021-09-20
  • 2019-02-03
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
  • 2011-04-29
相关资源
最近更新 更多