在较大的div

时间:2017-10-02 19:18:24

标签: javascript html css

我想在较大的div中分布不同宽度和高度的较小div,类似于这些pictures中显示的布局。在一个整页div中,我不会有超过4个较小的div。根据大小,单个整页容器可能有2-4个div,平均为3。 目前,我可以在较大的容器中放置较小的容器而没有任何重叠,但是较小的divs群集注意到here

function getRandomColor() {
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += (Math.random() * 16 | 0).toString(16);
        }
        return color;
    }

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }

    function Rectangle(p1, p2) {
        this.p1 = p1;
        this.p2 = p2;
    }

    Rectangle.prototype.isInside = function (r) {
        function check(a, b) {
            return (
                a.p1.x <= b.p1.x && b.p1.x <= a.p2.x && a.p1.y <= b.p1.y && b.p1.y <= a.p2.y ||
                a.p1.x <= b.p2.x && b.p2.x <= a.p2.x && a.p1.y <= b.p2.y && b.p2.y <= a.p2.y ||
                a.p1.x <= b.p2.x && b.p2.x <= a.p2.x && a.p1.y <= b.p1.y && b.p1.y <= a.p2.y ||
                a.p1.x <= b.p1.x && b.p1.x <= a.p2.x && a.p1.y <= b.p2.y && b.p2.y <= a.p2.y
            );
        }
        return check(this, r) || check(r, this);
    }

function generateRectangles() {
    function genPoint() { return Math.random() * 300 | 0; }
    function genSize() { return 50 + Math.random() * 150 | 0; }

    var rectangles = [],
        r, sizea, sizeb, x, y, isInside, i, counter = 0;

    for (i = 0; i < 3; i++) {
        counter = 0;
        do {
            counter++;
            x = genPoint();
            y = genPoint();
            sizea = genSize();
            sizeb = genSize();
            r = new Rectangle(new Point(x, y), new Point(x + sizea, y + sizeb));
            isInside = rectangles.some(function (a) {
                return a.isInside(r);
            });
        } while (isInside && counter < 1000);
        counter < 1000 && rectangles.push(r);
    }
    return rectangles;
}

function drawRectangles(rectangles) {
    var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d");
    ctx.fillStyle = "grey";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    rectangles.forEach(function (a) {
        ctx.lineWidth = 1;
        ctx.strokeRect(a.p1.x + 0.5, a.p1.y + 0.5, a.p2.x - a.p1.x - 1, a.p2.y - a.p1.y - 1);
        ctx.fillStyle = getRandomColor();
        ctx.fillRect(a.p1.x + 0.5, a.p1.y + 0.5, a.p2.x - a.p1.x - 1, a.p2.y - a.p1.y - 1);
    });
}

var rectangles = generateRectangles();
drawRectangles(rectangles);

0 个答案:

没有答案