Public
Edited
Jul 2, 2023
Importers
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
SVG = {
const arr = (val) => (Array.isArray(val) ? val : [val]);
const setAttributes = (node, attrs) => {
for (let key in attrs)
if (attrs[key] !== null) node.setAttribute(key, attrs[key]);
};
const element = (name, attributes, content) => {
const e = DOM.element(`svg:${name}`, attributes);
if (content)
if (typeof content == "string") e.textContent = content;
else e.append(...content);
return e;
};
return {
svg: ([width, height], children, attrs) => {
const svg = DOM.svg(width, height);
setAttributes(svg, attrs);
svg.append(...arr(children));
return svg;
},
group: (pos, children, attrs) => {
if (!children) (children = pos), (pos = [0, 0]);
const transform = (pos[0] != 0 || pos[1] != 0) && {
transform: `translate(${pos[0]}, ${pos[1]})`
};
return element("g", { ...transform, ...attrs }, arr(children));
},
rect: ([width, height], { radius: r, ...attrs } = {}) => {
if (!r) return element("rect", { width, height, ...attrs });
else {
const arc = (dx, dy) => `a${r},${r} 0 0,1 ${dx},${dy}`;
const hside = (s) => `h${(width - 2 * r) * s} ${arc(r * s, r * s)}`;
const vside = (s) => `v${(height - 2 * r) * s} ${arc(-r * s, r * s)}`;
const d = `m${r},0 ${hside(1)} ${vside(1)} ${hside(-1)} ${vside(-1)}`;
return element("path", { d, ...attrs });
}
},
circle: (radius, attrs) => element("circle", { r: radius, ...attrs }),
ellipse: (rx, ry, attrs) => element("ellipse", { rx, ry, ...attrs }),
line: ([x1, y1], [x2, y2], attrs) =>
element("line", { x1, y1, x2, y2, ...attrs }),
polyline: (points, attrs) =>
element("polyline", { points: points.join(" "), ...attrs }),
path: (d, attrs) => element("path", { d, ...attrs }),
text: (text, attrs) => element("text", attrs, text),
viewbox: (x, y, W, H) => `${x} ${y} ${W} ${H}`,
setAttributes
};
}
Insert cell
Insert cell
genView = {
const [W, H] = [512, 512];
const gens = [...Array(100)].map((_) => [
W * Math.random(),
H * Math.random()
]);
const { svg, rect, line, polyline, circle, viewbox } = SVG;
const r = rect([W, H], { fill: "none", stroke: "grey" });
const l = line([0, 0], [W, H], { stroke: "black" });
const p = polyline(
[
[W / 2, 0],
[W, H],
[0, H],
[W / 2, 0]
],
{ fill: "none", stroke: "red" }
);
const toPoint = ([cx, cy]) => circle(10, { cx, cy });
const viewBox = viewbox(-10, -10, W + 21, H + 21);
return svg([200, 200], [r, l, p, ...gens.map(toPoint)], { viewBox });
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more