Published
Edited
Nov 19, 2020
2 stars
Insert cell
md`# SVG Path: Simple Shapes`
Insert cell
example = {
const svg = d3.create("svg").attr("width", 200).attr("height", 50);
svg.append("g").attr("transform", "translate(10, 10)")
.append("path").attr("d", star(5, 9, 4));
svg.append("g").attr("transform", "translate(30, 10)")
.append("path").attr("d", circle(8));
svg.append("g").attr("transform", "translate(50, 10)")
.append("path").attr("d", "M2 -8 v 6 h 6 v 4 h -6 v 6 h -4 v -6 h -6 v -4 h 6 v -6 Z");
svg.append("g").attr("transform", "translate(70, 10)")
.append("path").attr("d", "M0 -8 L8 8 L-8 8 Z");
svg.append("g").attr("transform", "translate(90, 10)")
.append("path").attr("d", "M-8 -8 v 16 h 16 v -16 Z");
svg.append("g").attr("transform", "translate(110, 10)")
.append("path").attr("d", polygon(6, 9));

return svg.node();
}
Insert cell
Insert cell
function star(n, outerR, innerR){
const outer = circlePoints(n, outerR, (360/n)/2);
const inner = circlePoints(n, innerR, 360/n);
const precision = 3;
let path = '';
for(let i = 0; i < n; i++) {
if(i === 0){
path += 'M ' + Number(outer[i].x).toFixed(precision) + ' ' + Number(outer[i].y).toFixed(precision) + ' ';
} else {
path += 'L ' + Number(outer[i].x).toFixed(precision) + ' ' + Number(outer[i].y).toFixed(precision) + ' ';
}
path += 'L ' + Number(inner[i].x).toFixed(precision) + ' ' + Number(inner[i].y).toFixed(precision) + ' ';
}
path += 'Z';
return path;
}
Insert cell
Insert cell
function polygon(n, r) {
const outer = circlePoints(n, r, (360/n)/2);
const precision = 3;
let path = '';
for(let i = 0; i < n; i++) {
if(i === 0){
path += 'M ' + Number(outer[i].x).toFixed(precision) + ' ' + Number(outer[i].y).toFixed(precision) + ' ';
} else {
path += 'L ' + Number(outer[i].x).toFixed(precision) + ' ' + Number(outer[i].y).toFixed(precision) + ' ';
}
}
path += 'Z';
return path;
}
Insert cell
md`
circle: make a circle shape

- @param r - radius of the circle
- @return a string for the d attribute of an svg path element
`
Insert cell
Insert cell
Insert cell
Insert cell
function circlePoints(pointsCount, r, offset){
const points = [];
let offsetDeg = offset * Math.PI * 2 / 360;
let baseAngle = Math.PI/2 + offsetDeg;
let intervalDeg = (360 / pointsCount) * Math.PI * 2 / 360;
for(let i = 0; i < pointsCount; i++) {
points.push({x: r * Math.cos(baseAngle + intervalDeg * i), y: r * Math.sin(baseAngle + intervalDeg * i)});
}
return points;
}
Insert cell
d3 = require("d3-selection")
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