Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <article class="stage">
	<h1>Path Derivations</h1>
	<p>All paths here are generated. Every consecutive path derives its coordinates from the previous path. This was just sketch for a completely different project. But I wondered what would happen if I were to just keep drawing lines? That's what this is.</p>
	<p>Big thanks to <a href="https://codepen.io/meodai/">David Aerne</a> for his knowledge & expertise! Check out his fork <a href="https://codepen.io/meodai/pen/85b4d368d9a522f7b7fc7e783dfccfc3">here</a>.</p>
	<div class="element" data-path-container></div>
	<div class="stage__controls">
		<button data-button-redraw>
			<span class="text">redraw</span>
		</button>
		<button data-button-fill>
			<span class="text">fill</span>
		</button>
		<button data-button-add-top>
			<span class="text">add one</span>
		</button>
	</div>
	<p>Play with the generation in the extrudeUp & extrudeDown function, as well as the settings object, to change the outcome.</p>
</article>
              
            
!

CSS

              
                * {
	box-sizing: border-box;
}

body {
	--main-color: #ffa07a;
	--text-color: #641c00;
	--secondary-color: #6A5ACD;
	display: grid;
	place-items: center;
	background-color: mistyrose;
	min-height: 100vh;
	font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
	padding: clamp(1.5em, 7vmin, 4em);
	color: var(--text-color);
}

a {
	color: var(--secondary-color);
	text-underline-offset: 3px;
	text-decoration-thickness: 2px;
	
	&:is(:hover, :focus) {
		color: var(--main-color);
	}
}

.sr-only {
	clip: rect(0 0 0 0); 
    clip-path: inset(50%);
    height: 1px;
    overflow: hidden;
    position: absolute;
    white-space: nowrap; 
    width: 1px;
}

.stage {
	width: max(70vw, 600px);
	background-color: #fff;
	border-radius: 10px;
	padding: 4em;
	display: flex;
	flex-direction: column;
	gap: 2em;
	
	h1 {
		font-size: 2em;
		font-weight: 650;
		color: var(--main-color);
	}
	
	p {
		line-height: 1.5;
	}
	
	&__controls {
		display: flex;
		justify-content: center;
		gap: 1em;
		
		button {
			--shadow: 10%;
			line-height: 1;
			gap: .5em;
			display: inline-flex;
			align-items: center;
			background-color: var(--main-color);
			border: none;
			padding: .4em 1em .45em;
			border-radius: 4px;
			color: currentcolor;
			box-shadow: inset 0px -2px 0px rgb(0 0 0 / var(--shadow));
			border: 2px solid currentcolor;
			font-size: 1em;

			.icon {
				display: inline-block;
				width: 1.5em;
			}
			
			&:is(:hover, :focus) {
				--shadow: 20%;
				cursor: pointer;
				transform: translateY(1px);
			}
			
			&:active {
				--shadow: 30%;
				transform: translateY(2px);
			}
		}
	}
}

.element {
	aspect-ratio: 2/1;
	border: 2px solid var(--text-color);
	border-radius: 5px;
	overflow: hidden;
	display: block;
	
	path {
		fill: transparent;
	}
}
              
            
!

JS

              
                // utils
const randomBetween = (_min, _max) => Math.floor( Math.random() * (_max - _min +1) + _min );
const maybe = () => Math.round(Math.random());
const modifySafely = (_from, _by, _or, _mode = "add") => {
	if (_mode === "add") {
		return Math.max(_from * _by, _from + _or);
	} else {
		return Math.min(_from / _by, _from - _or);
	}
};

/*
	Abstract Core Functions
*/

// draws a path to the given coordinates
const drawPath = (_element, _coords, _mirrorHandle = false) => {
	const { start, handle, end } = _coords;
	
	if (_mirrorHandle) {
		_element.plot(`
			M ${start.x},${start.y}
			Q ${handle.x},${handle.y} ${end.x/2},${end.y}
			t ${end.x/2},0
		`);
	} else {
		_element.plot(`
			M ${start.x},${start.y}
			Q ${handle.x},${handle.y} ${end.x},${end.y}
		`);
	}
}

// draws a path with randomly generated positions
const drawRandomPath = (_element, _dimension, _secondCurve = false) => {
	const startY = randomBetween(0, _dimension.h);
	// try to make sure that the handle is definitely not the same as the start
	const modifyStartSafely = () => {
		if (maybe()) {
			return Math.min(randomBetween(0, _dimension.h), startY * 25);
		} else {
			return Math.max(randomBetween(0, _dimension.h), startY / 25);
		}
	}
	
	const coords = {
		start: {
			x: 0,
			y: startY
		},
		handle: {
			x: randomBetween(0, _dimension.w),
			y: modifyStartSafely()
		},
		end: {
			x: _dimension.w,
			y: randomBetween(0, _dimension.h)
		}
	}
	
	drawPath(_element, coords, _secondCurve);
	return coords;
}

// modify coordinates
const extrudeUp = (_coords, {factor, distance}, _dimension) => {
	const { start, handle, end } = _coords;
	const modify = _from => modifySafely(_from, factor, distance, false);
	
	return {
		start: {
			x: start.x,
			y: modify(start.y)
		},
		handle: {
			x: Math.min(handle.x / factor, _dimension.w),
			y: handle.y
		},
		end: {
			x: end.x,
			y: modify(end.y)
		}
	};
}
const extrudeDown = (_coords, {factor, distance}, _dimension) => {
	const { start, handle, end } = _coords;
	const modify = _from => modifySafely(_from, factor, distance);
	
	return {
		start: {
			x: start.x,
			y: modify(start.y)
		},
		handle: {
			x: Math.min(handle.x * factor, _dimension.w),
			y: handle.y
		},
		end: {
			x: end.x,
			y: modify(end.y)
		}
	};
}

// vars
const container = document.querySelector('[data-path-container]');
const generated = document.querySelectorAll('[data-generate]');
const redraw = document.querySelector('[data-button-redraw]');
const addUp = document.querySelector('[data-button-add-top]');
const fill = document.querySelector('[data-button-fill]');

// setup
let dimension = {
	w: container.offsetWidth,
	h: container.offsetHeight
};

// settings
const twoCurves = false;
const derivative = {
	factor: 1.15,
	distance: dimension.h / 20
};
const baseStrokeWidth = dimension.w * .00337;

// this will hold the coordinates of every generated path, so that every newly generated path can be derived from it
let paths = [];

// Create the stage
const canvas = SVG()
	.addTo(container)
	.size(container.offsetWidth, container.offsetHeight)
	.viewbox(0, 0, dimension.w, dimension.h);

const canvasBounds = canvas.node.getBoundingClientRect();

/*
	Stage-Aware functions to 
*/
const addRandomPath = () => {
	const path = new SVG.Path(); 
	paths = [];
	canvas.clear();
	paths.push(drawRandomPath(path, dimension, twoCurves));
	canvas.add(path);
	const length = path.length();
	path.attr({
		opacity: 0,
		stroke: '#FFA07A',
		'stroke-dasharray': length,
		'stroke-dashoffset': length,
		'stroke-width': baseStrokeWidth
	});
	path.animate({
		duration: 400,
		swing: true
	}).attr({
		opacity: 1,
		'stroke-dashoffset': 0
	});
}

// add a path on top
const addTopPath = (_color = '#FFA07A') => {
	const newCoords = extrudeUp(paths[paths.length - 1], derivative, dimension);
	paths.push(newCoords);
	const newPath = new SVG.Path();
	drawPath(newPath, newCoords, twoCurves);
	canvas.add(newPath);
	const length = newPath.length();
	newPath.attr({
		opacity: 0,
		stroke: _color,
		'stroke-dasharray': length,
		'stroke-dashoffset': length,
		'stroke-width': baseStrokeWidth
	});
	newPath.animate({
		duration: 400,
		swing: true
	}).attr({
		'stroke-dashoffset': 0,
		opacity: 1
	});
}

// add a path on bottom
const addBottomPath = (_color = '#6A5ACD') => {
	const newCoords = extrudeDown(paths[paths.length - 1], derivative, dimension);
	paths.push(newCoords);
	const newPath = new SVG.Path();
	drawPath(newPath, newCoords, twoCurves);
	newPath.stroke(_color);
	canvas.add(newPath);
}

// fill the remaining space in a direction with paths.
// This function was mainly optimized for what it was intended to do by David Aerne
const fillWithPaths = (_direction = 'top', _i = 0, _maxIterations = 50) => {
	const extrude = _direction === 'top' ? extrudeUp : extrudeDown;
	const newCoords = extrude(paths[paths.length - 1], derivative, dimension);
	paths.push(newCoords);
	const newPath = new SVG.Path();
	drawPath(newPath, newCoords, twoCurves);
	canvas.add(newPath);
	const newPathLength = newPath.length();
	newPath.attr({
		opacity: 0,
		stroke: '#ffa07a',
		'stroke-dasharray': newPathLength,
		'stroke-dashoffset': newPathLength,
		'stroke-width': baseStrokeWidth
	});
	
	// get in some movement
	newPath.animate({
		duration: 1500 - (_i * 75),
		swing: true,
		when: 'relative',
		delay: _i * 75
	}).attr({
		opacity: 1,
		'stroke-dashoffset': 0,
		'stroke-width': (Math.max((baseStrokeWidth + _i) / 2, 2))
	}).animate({
		delay: 750,
		duration: 750,
		swing: true
	}).attr({
		stroke: _direction === 'top' ? '#ffa07a':'#6A5ACD'
	});

	// This specific part detects whether the generated curves are stil within the bounds of the element. This was entirely written by David Aerne. Thanks!
	const newPathBox = newPath.node.getBBox();
	
	if ( _direction === 'top' ) {
		if ( (newPathBox.y + newPathBox.height) > 0 && _i < _maxIterations) {
			fillWithPaths(_direction, _i+1);
		}
	} else {
		if (newPathBox.y < dimension.h && _i < _maxIterations) {
			fillWithPaths(_direction, _i+1);
		}
	}
}

// get ramining possible length of a given coordinate
const remainingLength = (_coordinate, _dimension = dimension.h) => {
	
};

// draw the initial path
addRandomPath();

// redraw the path on click
redraw.addEventListener('click', () =>  addRandomPath());

// add a new Path on top based on the previously generated path
addUp.addEventListener('click', () => addTopPath());

// fill the remaining space up with lines
fill.addEventListener('click', () => {
	const lastPath = paths[paths.length - 1];
	
	// draw Start segments up
	fillWithPaths('top');
	
	// reset the path back to the initially generated path
	paths.push(lastPath);
	

	// draw segments down
	fillWithPaths('bottom');
	
});
              
            
!
999px

Console