Trying to create x number of random rectangles by iterating through loop - but no overlapping

前端 未结 2 1240
无人及你
无人及你 2021-01-20 18:00

This one has be me stumped. This is more of a Math/logic issue then a specific JS issue, but it\'s JS that I am working in and and some point I will need to convert the resu

2条回答
  •  死守一世寂寞
    2021-01-20 18:39

    This is a cool idea!

    You can think about it terms of boxes in boxes (also like a tree). These boxes have their own coordinates and sizes. Boxes can be inside boxes so to do this you pick a dimension to split on (horizontally or vertically) then divide up for however many boxes. Then in each of those boxes you can add more boxes, etc. Finally to draw the lines you just equip boxes with the ability to draw themselves (and tell their boxes to draw themselves).

    Below is some JS that does this. You can play with how much nesting you want to do pretty easily. The thing that is a little tricky and might need some adjusting is determining how to split the space into roughly even boxes (randomly different by a little bit). What's I've done to split the space into n boxes is to start with the size being 1/n of the available space, then randomly nudging it a little. If you just go with remaining*Math.random() most of the time you'll end up with very narrow boxes.

    // probably play around with this to get better splitting
    // maybe split near a mouse click
    let splitDimension = (l, n) => {
        let splits = [];
        let remaining = l;
        let x = 0;
        for (let i=0; i {
                box.draw(ctx)
            });
        }
    
        addBoxes(n, dim) {
            let splits;
            if (dim == "x") {
                // split on width
                splits = splitDimension(this.w, n)
                // turn the splits into new boxes
                this.boxes = splits.map(([x,w]) => {
                    return new Box(this.x+x, this.y, w, this.h)
                });
            } else {
                // split over height
                splits = splitDimension(this.h, n);
                this.boxes = splits.map(([y,h]) => {
                    return new Box(this.x, this.y+y, this.w, h);
                })
            }
        }
    }
    let canvas = document.querySelector("canvas");
    let ctx = canvas.getContext("2d");
    // let's make some boxes!
    let bigBox = new Box(0,0,canvas.width,canvas.height);
    bigBox.addBoxes(2, "y");
    // now add boxes on boxes on boxes
    bigBox.boxes.forEach(box => {
        box.addBoxes(3, "x");
        // also more boxes
        box.boxes.forEach(boxBox => {
            boxBox.addBoxes(2, "y");
        });
    });
    // now draw the boxes!
    bigBox.draw(ctx);
    

提交回复
热议问题