有关我遇到的问题的演示,请参阅此[fiddle][removed]。
基本上,我正在生成一条接触正方形墙壁的线#block
。问题是这些行似乎没有像我预期的那样分布(在添加了足够的行之后)。这是我期望的输出:
这是我得到的输出:
您可以通过点击add 100按钮重新创建它。我似乎无法弄清楚为什么线的最大长度在底部的线高度集中,但在最小长度附近的集中度却如此低。具体来说,这里是我如何生成线的长度,其中最小值是正方形宽度的一半,最大值是从中心到角的距离(用勾股定理计算):
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
问题的症结在于我想得到我期望的输出,线条完全填满这个 45 度的部分,而不是挤在底部。
完整代码:
HTML
<div id="block"></div>
<button id="add">add</button>
<button id="add100">add 100</button>
<button id="clear">clear</button>
<label id="count">0 lines</label>
CSS
#block {
width:200px;
height:200px;
border:1px solid black;
}
.line {
position:absolute;
width:1px;
-webkit-transform-origin: 0% 0%;
background-color:black;
}
JS
$('#add').click(function () {
//generate a div with a random id
var lineId = Math.floor(Math.random() * 32768);
$('#block').append('<div class="line" id="line' + lineId + '"></div>');
var curLine = $('#line' + lineId);
$('#count').html($('#block > div').size() + " lines");
//get properties of the block
var xmax = parseInt($('#block').css("height"), 10); //200
var ymax = parseInt($('#block').css("width"), 10); //200
//(xcen, ycen) is the origin of the points
var xcen = xmax / 2;
var ycen = ymax / 2;
curLine.css("left", (xcen + 9) + "px"); //9 is horizontal offset
curLine.css("top", (ycen + 8) + "px"); //8 is vertical offset
//the longest line would go from the origin to the corner: the hypotenuse
var maxlen = Math.sqrt((xcen * xcen) + (ycen * ycen));
//the shortest line would go from the origin straight up: the shortest leg
var minlen = (xcen <= ycen) ? xcen : ycen;
//the length of the line will be between the shortest length, and longest
var height = getRandomInt(minlen, maxlen);
curLine.css("height", height + "px");
// arcsin (opposite/hypotenuse) converted to degrees
var angle = Math.asin(xcen / height) * (180 / Math.PI);
curLine.css('transform', 'rotate(' + angle + 'deg)');
curLine.css('-webkit-transform', 'rotate(' + angle + 'deg)');
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$('#add100').click(function () {
for (var i = 0; i < 100; i++)
$('#add').trigger('click');
});
$('#clear').click(function () {
$('.line').remove();
$('#count').html($('#block > div').size() + " lines");
});