Published
Edited
May 21, 2021
Insert cell
md`# Place random rectangle in a box`
Insert cell
svg = {
const rectangles = generateRectangles();
const svg = d3.create("svg").attr("viewBox", [0, 0, 400, 200]);
const g = svg.append("g");

g.selectAll("rect")
.data(rectangles)
.join("rect")
.attr("x", d => d.p1.x + 20)
.attr("y", d => d.p1.y + 0.5)
.attr('width', d => d.p2.x - d.p1.x - 1)
.attr('height', d => d.p2.y - d.p1.y - 1)
.style('fill', (d, i) => getRandomColor());

svg.call(
d3
.zoom()
.extent([[0, 0], [400, 200]])
.scaleExtent([1, 10])
.on("zoom", zoomed)
);
function zoomed({ transform }) {
g.attr("transform", transform);
}

return svg.node();
}
Insert cell
function getRandomColor() {
var color = '#';
for (var i = 0; i < 6; i++) {
color += (Math.random() * 16 | 0).toString(16);
}
return color;
}
Insert cell
function Point(x, y) {
this.x = x;
this.y = y;
}

Insert cell
function Rectangle(p1, p2) {
this.p1 = p1;
this.p2 = p2;
}
Insert cell
(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);
})
Insert cell
function generateRectangles() {
function p() {
return (Math.random() * 100) | 0;
}
function s() {
return (25 + Math.random() * 50) | 0;
}

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

for (i = 0; i < 20; i++) {
counter = 0;
do {
counter++;
x = p();
y = p();
size = s();
r = new Rectangle(new Point(x, y), new Point(x + size, y + size));
isInside = rectangles.some(function(a) {
return a.isInside(r);
});
} while (isInside && counter < 1000);
counter < 1000 && rectangles.push(r);
}
return rectangles;
}
Insert cell
d3 = require("d3@6")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more