Published
Edited
Feb 25, 2022
Insert cell
# Prepare for Inkscape
Insert cell
Insert cell
viewof imgFile = Inputs.file({
label: "Image",
accept: ".svg",
required: true
})
Insert cell
Insert cell
Insert cell
render = {
const img = await imgFile.text();
const theSvg = d3.select(svg`${img}`);

theSvg.select('image').remove();
theSvg.style('stroke', penGray);

// Find all points in all paths to compute a bounding box
const pathPoints = theSvg.selectAll('path').nodes().map(pathNode => pathNode.getPathData())
.flatMap(path => path.map(point => point.values));
const pathHull = d3.polygonHull(pathPoints);
const leastX = d3.min(pathHull, ([x, y]) => x),
mostX = d3.max(pathHull, ([x, y]) => x),
leastY = d3.min(pathHull, ([x, y]) => y),
mostY = d3.max(pathHull, ([x, y]) => y);

const pathWidth = mostX - leastX,
pathHeight = mostY - leastY;
const pathMarginX = 0 * pathWidth,
pathMarginY = 0 * pathHeight;

const newWidth = pathWidth + 2 * pathMarginX,
newHeight = pathHeight + 2 * pathMarginY;
const widthToHeight = newWidth / newHeight;

// theSvg.attr('height', 700)
// .attr('width', widthToHeight * 500);

theSvg.attr('width', newWidth)
.attr('height', newHeight)
.attr('viewBox', [leastX - pathMarginX, leastY - pathMarginY,
newWidth, newHeight
].join(' '))

// Set all path widths to a uniform 1, and set color to reasonable gray
theSvg.selectAll('path').attr('stroke-width', 1)
.attr('stroke', penGray)
.style('stroke', penGray)
.attr('fill', 'none');

theSvg.selectAll('g').style('stroke', penGray);

// simplify all paths
theSvg.selectAll('path')
.attr('d', function (_, i) {
const existingDString = d3.select(this).attr('d');
let simplified;
try {
simplified = simplifyPathDString(existingDString);
} catch (e) {
debugger;
}
return simplified;
})

return theSvg.node();
}
Insert cell
Insert cell
Insert cell
import {simplify, simplifyPathDString}
with {simplificationTolerance as tolerance}
from '@tstodter/simplify-path'
Insert cell
import {dStringToPoints}
from '@tstodter/path-d-parser'
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