gpt4 book ai didi

javascript - 如何创建动态网格

转载 作者:太空宇宙 更新时间:2023-11-04 14:05:52 26 4
gpt4 key购买 nike

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

最佳答案

这是将@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>

关于javascript - 如何创建动态网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21117684/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com