gpt4 book ai didi

javascript - 用随机大小的形状填充框

转载 作者:行者123 更新时间:2023-11-29 16:15:40 26 4
gpt4 key购买 nike

我需要填充一个固定大小的盒子,它应该填充 9 随机 大小的形状。

因为我有 9 个形状,一个或多个可以在另一个之上,这样做的目的是创造随机效果,就好像这些形状是随机散布的一样。但是话又说回来,不能有任何空白,这是非常重要也是最困难的部分。

所以想象一下我做得更好的地方以及这应该是什么样子的例子

enter image description here

而且我还设置了jsFiddle,你看看吧here

我为此工作了几个小时,但无论我想到什么都行不通,所以这只是我使用代码所做的一个非常基本的示例。

我并不是要一个完整的工作代码,但是关于我应该如何从这一点继续下去的任何类型的建议都会有很大帮助。

因为 SO 规则要求 jsFiddle 代码,所以这里是:

$shape = $('<div class="shape"></div>');
$container = $(".container");

//random shape sizes
shapes = [
[rand(50, 70), rand(50, 70)],
[rand(50, 70), rand(50, 70)],
[rand(60, 70), rand(60, 70)],
[rand(60, 100), rand(60, 100)],
[rand(100, 140), rand(100, 140)],
[rand(100, 140), rand(100, 140)],
[rand(100, 140), rand(100, 140)],
[rand(140, 190), rand(140, 190)],
[rand(150, 210), rand(150, 210)]
];

used = [];
left = 0;
top = 0;

for(i = 1; i <= 3; i++){
offset = rand(0, 8);

width = shapes[offset][0];
height = shapes[offset][1];

$container.append(
$shape.css({
width: width,
height: height,
top: top,
left: left,
zIndex: i
})
.text(i)
.clone()
);

//increase top offset
top += shapes[offset][1];
}


function rand(from, to){
return Math.floor((Math.random()*to)+from);
}

最佳答案

实际上答案非常困难,我们可以深入研究它,因为您需要某种空间填充算法。

老实说,我对这类事情不是很感兴趣,但我建议 - 如果你能处理它 - 进入这个主题:

  • 分形填充算法
  • 质心松弛的 Voronoi 细胞
  • 二叉树

我试着写下后者的简单实现,即二叉树。它的工作原理是递归地将空间区域分割为更小的部分。

var square = {x: 0, y: 0, width: 200, height: 200};
var struct = [square];

function binary(struct) {
var axis = 1;
function subdivide(index) {
var item = struct.splice(index, 1)[0];
if(axis > 0) {
var aw = item.width / 2;
var ow = Math.random() * aw;
ow -= ow / 2;
var ax = Math.round(item.width / 2 + ow);
var bx = item.width - ax;
struct.push({x: item.x, y: item.y, width: ax, height: item.height});
struct.push({x: item.x + ax, y: item.y, width: bx, height: item.height});
} else {
var ah = item.height / 2;
var oh = Math.random() * ah;
oh -= oh / 2;
var ay = Math.round(item.height / 2 + oh);
var by = item.height - ay;
struct.push({x: item.x, y: item.y, width: item.width, height: ay});
struct.push({x: item.x, y: item.y + ay, width: item.width, height: by});
}

axis = -axis;
}

while(struct.length < 9) {
var index = Math.round(Math.random() * (struct.length-1));
subdivide(index);
}

return struct;
}

打电话

binary(struct);

返回一个分割区域数组。希望这可以成为一个起点(而且我假设你不想运行内存密集型算法将图像随机放置在一个盒子里,但我可能是错的:))

关于javascript - 用随机大小的形状填充框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16526067/

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