Skip to content

Instantly share code, notes, and snippets.

@starakaj
Created April 16, 2021 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starakaj/7b12f9e7253d089013640f9fe92b82aa to your computer and use it in GitHub Desktop.
Save starakaj/7b12f9e7253d089013640f9fe92b82aa to your computer and use it in GitHub Desktop.
// ...
// Note the code to specify relative coordinates.
// This will enable relative coordinates and ALSO
// tell Max to resize the drawing automatically.
const makePaintFunction = template(`
mgraphics.relative_coords = 1;
function paint() {
%%statements%%
}
`);
function translateSource(data: string, outPath: string) {
let paintStatements: t.Statement[] = [];
let viewBox: number[];
const parser = new html2.Parser({
onopentag(name: string, attribs: {[s: string]: string}) {
if (name === "rect") {
if (viewBox !== undefined) {
let x = t.numericLiteral(
// Scale the absolute coordinates of each rectangle according
// to the bounds of the parent view box.
2 * Number.parseFloat(attribs.x || "0") / viewBox[2] - 1
);
let y = t.numericLiteral(
2 * Number.parseFloat(attribs.y || "0") / viewBox[3] - 1
);
let w = t.numericLiteral(
2 * Number.parseFloat(attribs.width || "0") / viewBox[2]
);
let h = t.numericLiteral(
2 * Number.parseFloat(attribs.height || "0") / viewBox[3]
);
const rectStatements = makeRectDrawStatements({ x, y, w, h });
paintStatements = paintStatements.concat(rectStatements);
} else {
console.warn("rect tag outside of svg parent tag with defined viewBox, skipping");
}
}
else if (name === "svg") {
// When you enter the root svg tag, set the bounds of the viewBox
// Split the viewbox string on spaces and convert to numbers
viewBox = attribs["viewbox"].split(" ").map(Number.parseFloat);
}
}
});
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment