如何创建动态网格 [英] How to create dynamic grid
本文介绍了如何创建动态网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用动态宽度和高度创建一个网格。确保每个单元格区域的宽度和高度相等的公式是什么?
i am trying to create a grid with using dynamic width and height. What is the formula to make sure each cell area is of equal width and height?
推荐答案
这里是@ Teepemm的想法放入代码。
Here's @Teepemm's idea put into code.
如果您希望所有宽度与其他宽度相同,并且所有高度都与其他高度相同:
If you want all widths to be the same as other widths and all heights to be the same as other heights:
var xSpan=cw/lineCount;
var ySpan=cw/lineCount;
如果你想要方形单元格(width == height),那么只需使用1 span。注意:在这种情况下,单元格的底行可能不是正方形:
If you want square cells (width==height) then just use 1 span. Note: in this case the bottom row of cells may not be square:
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>
这篇关于如何创建动态网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文