Skip to content

Instantly share code, notes, and snippets.

@revdancatt
Created May 20, 2026 09:54
Show Gist options
  • Select an option

  • Save revdancatt/87237ae768ab6015aaa65918bbdf2cfa to your computer and use it in GitHub Desktop.

Select an option

Save revdancatt/87237ae768ab6015aaa65918bbdf2cfa to your computer and use it in GitHub Desktop.
Nodejs file for making a pen plot "ribbon" design
// @revdancatt
// penplotter.com
// revdancatt.com
const fs = require('fs')
const path = require('path')
const sizes = {
A6: {
width: 105,
height: 148,
margins: { top: 12, right: 12, bottom: 12, left: 12 },
radius: 18
},
A5: {
width: 148,
height: 210,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
radius: 18
},
A4: {
width: 210,
height: 297,
margins: { top: 22, right: 22, bottom: 22, left: 22 },
radius: 18
},
A3: {
width: 297,
height: 420,
margins: { top: 32, right: 32, bottom: 32, left: 32 },
radius: 18
},
FANCY: {
width: 760,
height: 565,
margins: { top: 30, right: 30, bottom: 30, left: 30 },
radius: 18
},
FANCYOUTER: {
width: 760,
height: 565,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
radius: 18
}
}
const keepPercentages = [
{ chance: 0.666, name: '00_high' },
{ chance: 0.666 * 0.666, name: '01_medium' },
{ chance: 0.666 * 0.666 * 0.666, name: '02_low' }
]
const strokeColours = ['#d8432e', '#1f1f1f', '#2762c7']
function generateLines (paperKey, rows, innerGap, keepPercentIndex) {
const paper = sizes[paperKey]
if (!paper) throw new Error(`Unknown paper size "${paperKey}".`)
const lines = []
const keepChance = keepPercentages[keepPercentIndex].chance
// Work out the length of the line. The space we have to play in is basically the height of the paper
// less the margins, less the gaps inbeteen the rows. The divide that by the num of rows.
const lineLength = (paper.height - paper.margins.top - paper.margins.bottom - innerGap * (rows - 1)) / rows
// When we make a fan, we "pivot" around the mid-point of the gap
const turnSize = lineLength + innerGap / 2
// Start by going left to right
let leftToRight = true
for (let i = 0; i < rows; i++) {
// Work out the top of the line position
const startY = paper.margins.top + (lineLength + innerGap) * i
// this bit is easy
const endY = startY + lineLength
// First row starts at the margin. After that until the last one we need to
// leave room for the 'fan' to turn
let startX = paper.margins.left
if (i > 0) startX += turnSize
// Middle rows leave room at the both the start and end of the row
let endX = paper.width - paper.margins.right
// I may be fucking this up but if we're NOT
// the last row we also need to take of the turning size
if (i < Math.floor(rows / 2) * 2) endX -= turnSize
// Going right-to-left just means flipping start/end and using -1 as the step direction
let directionModifier = 1
if (!leftToRight) {
directionModifier = -1
// Ugh, can't remember how to do the job-interview values swap
const tempX = startX
startX = endX
endX = tempX
}
// Walk across the row dropping vertical lines, randomly skipped and randomly spaced
let x = startX
while (directionModifier > 0 ? x < endX : x > endX) { // <- I hate this
if (Math.random() < keepChance) {
lines.push([{ x, y: startY }, { x, y: endY }])
}
// Next line position is randomly something
x += directionModifier * (Math.random() * 2 + 0.5)
}
// Now it's time to do the turn (unless we're the last line, obvs)
if (i < rows - 1) {
// Draw the curved turn connecting this row to the next.
// We sweep an angle from ~0° to 180°, rotating two points (inner/outer edge of the turn)
// around the corner — which fans out into a half-circle of short segment things.
const startAngleDeg = (Math.random() * 5 + 2.5) / 2
const endAngleDeg = 180
let thisAngleDeg = startAngleDeg
const p1 = { x: 0, y: -innerGap / 2 } // inner radius
const p2 = { x: 0, y: -(innerGap / 2) - lineLength } // outer radius
// Yay, while ❤️
while (thisAngleDeg <= endAngleDeg) {
const rads = (thisAngleDeg * Math.PI) / 180
// Don't need to optimize this, we're not Quake or Doom
const rx1 = Math.sin(rads) * p1.y
const ry1 = Math.cos(rads) * p1.y
const rx2 = Math.sin(rads) * p2.y
const ry2 = Math.cos(rads) * p2.y
// Flip the x direction depending on which way we came in
// Pretty sure there's a neater way of doing this
if (Math.random() < keepChance) {
if (leftToRight) {
lines.push([
{ x: endX - rx1, y: ry1 + endY + innerGap / 2 },
{ x: endX - rx2, y: ry2 + endY + innerGap / 2 }
])
} else {
lines.push([
{ x: endX + rx1, y: ry1 + endY + innerGap / 2 },
{ x: endX + rx2, y: ry2 + endY + innerGap / 2 }
])
}
}
// The amount we add to the angle should probably be tied
// to the amount we step forwards lines on along the
// row, doesn't really make sense to adjust this is two places
// but it's not like I'm going to change this much!
thisAngleDeg += Math.random() * 5 + 2.5
}
}
leftToRight = !leftToRight
}
return lines
}
function assignColours (lines) {
const linesColour1 = []
const linesColour2 = []
const linesColour3 = []
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
const progress = lines.length <= 1 ? 0 : i / (lines.length - 1)
// We want to tend towards the first colour at the start,
// the last colour at the end, and the middle in, well,
// the middle. There's a more general way of doing this for X number
// of colours, but honestly three is enough for this.
const colour1Weight = Math.max(0, 1 - progress / 0.66)
const colour2Weight = Math.max(0, 1 - Math.abs(progress - 0.5) / 0.335)
const colour3Weight = Math.max(0, (progress - 0.33) / 0.67)
const totalWeight = colour1Weight + colour2Weight + colour3Weight
const pick = Math.random() * totalWeight
// I kinda hate this
if (pick < colour1Weight) linesColour1.push(line)
else if (pick < colour1Weight + colour2Weight) linesColour2.push(line)
else linesColour3.push(line)
}
// Seperated the lines out into three buckets
return [linesColour1, linesColour2, linesColour3]
}
function buildSvgBody (colourLines) {
return colourLines
.map((line, lineIndex) => {
// Alternate the direction of the line, in the tutorial version this is a lot
// easier to read, but fuck it, no-one is going to see this.
const start = lineIndex % 2 === 0 ? line[0] : line[1]
const end = lineIndex % 2 === 0 ? line[1] : line[0]
return ` <path d="M ${start.x.toFixed(3)},${start.y.toFixed(3)} ${end.x.toFixed(3)},${end.y.toFixed(3)}" />`
})
.join('\n')
}
function svgDocument (paper, strokeColour, body) {
const width = paper.width
const height = paper.height
return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="${width}mm"
height="${height}mm"
viewBox="0 0 ${width} ${height}"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="${width}" height="${height}" fill="white" />
<g style="fill:none;stroke:${strokeColour};stroke-width:0.2mm;stroke-linecap:round">
${body}
</g>
</svg>
`
}
// 'cause I is fancy!
function printHelp () {
const keys = Object.keys(sizes).join(', ')
console.log(`Things for the Patron peeps!!
Usage:
node autotrack.js --cards <n> [options]
Options:
--cards <n> How many card folders to generate (default: 1)
--paper <name> Paper preset: ${keys} (default: A5)
--rows <n> Row count (default: 3, no wait, 5)
--gap <mm> Inner gap between rows in mm (default: 12)
--out-dir <path> Base output directory (default: ./track-output-cards)
--mode <name> all | high | medium | low (default: all)
all = 9 SVGs per card; high/medium/low = 3 SVGs (one tier)
Examples:
node autotrack.js --cards 10
node autotrack.js --cards 2 --paper A6 --rows 5 --gap 8
node autotrack.js --cards 1 --mode high
`)
}
// I should probably import some library to do this, but this is 'good enough'
function parseArgs (argv) {
const args = {
cards: 1,
paper: 'A5',
rows: 5,
gap: 12,
outDir: path.join(process.cwd(), 'track-output-cards'),
mode: 'all',
help: false
}
for (let i = 2; i < argv.length; i++) {
const t = argv[i]
if (t === '--help' || t === '-h') {
args.help = true
continue
}
if (!t.startsWith('--')) throw new Error(`Unknown argument "${t}". Use --help.`)
const key = t.slice(2)
const val = argv[i + 1]
if (val == null || val.startsWith('--')) throw new Error(`Missing value for --${key}`)
i++
if (key === 'cards') args.cards = parseInt(val, 10)
else if (key === 'paper') args.paper = String(val).toUpperCase()
else if (key === 'rows') args.rows = parseInt(val, 10)
else if (key === 'gap') args.gap = parseFloat(val)
else if (key === 'out-dir') args.outDir = path.resolve(process.cwd(), val)
else if (key === 'mode') args.mode = val.toLowerCase()
else throw new Error(`Unknown option --${key}. Use --help.`)
}
// And yet, I will still somehow screw this up
if (!Number.isFinite(args.cards) || args.cards < 1) throw new Error('--cards must be an integer >= 1.')
if (!Number.isFinite(args.rows) || args.rows < 1) throw new Error('--rows must be an integer >= 1.')
if (!Number.isFinite(args.gap) || args.gap < 0) throw new Error('--gap must be a number >= 0.')
if (!sizes[args.paper]) throw new Error(`Unknown --paper "${args.paper}".`)
const modes = new Set(['all', 'high', 'medium', 'low'])
if (!modes.has(args.mode)) throw new Error('--mode must be one of: all, high, medium, low.') // YEAH!
return args
}
// helper
function keepIndicesForMode (mode) {
if (mode === 'all') return [0, 1, 2]
if (mode === 'high') return [0]
if (mode === 'medium') return [1]
if (mode === 'low') return [2]
return [0, 1, 2]
}
// Ok, let's go
function main () {
const args = parseArgs(process.argv)
if (args.help) {
printHelp()
process.exit(0)
}
const paper = sizes[args.paper]
fs.mkdirSync(args.outDir, { recursive: true })
// ooooooooooooh!
const keepIdxList = keepIndicesForMode(args.mode)
// MAKE ALL THE CARDS!!
for (let card = 0; card < args.cards; card++) {
const folderName = `track_${String(card).padStart(3, '0')}`
const cardDir = path.join(args.outDir, folderName)
fs.mkdirSync(cardDir, { recursive: true })
for (const keepIdx of keepIdxList) {
// Make the lines
const lines = generateLines(args.paper, args.rows, args.gap, keepIdx)
// Sort them into buckets
const buckets = assignColours(lines)
// Grab the teir name
const tierName = keepPercentages[keepIdx].name
// We know we have 3 buckets, we could generalise this I guess
for (let c = 0; c < 3; c++) {
const colourLines = buckets[c]
const body = buildSvgBody(colourLines)
// Make it so the files will sort nicely, from dense to sparse
const fileName = `${tierName}-colour_${c + 1}.svg`
const filePath = path.join(cardDir, fileName)
fs.writeFileSync(filePath, svgDocument(paper, strokeColours[c], body), 'utf8')
console.log('Wrote', filePath)
}
}
}
console.log(`Done. ${args.cards} card folder(s) under ${args.outDir}`)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment