Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ 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

Save Automatically?

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

              
                <!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0" />

		<title>React SVG Donut</title>

		<style>
			body {
				margin: 0;
			}

			.demo {
				display: flex;
				flex-flow: row wrap;
				align-items: center;
				justify-content: center;
				padding: 1rem;
			}

			.pie {
				margin: 1rem;
			}
		</style>
	</head>

	<body>
		<div id="demo1" class="demo"></div>

		<div id="demo2" class="demo"></div>
	</body>
</html>

              
            
!

CSS

              
                @keyframes donut-fill {
	to {
		stroke-dasharray: 0 100;
	}
}

@keyframes text-slideup {
	from {
		opacity: 0;
		transform: translateY(0%);
	}
	to {
		opacity: 1;
		transform: translateY(-50%);
	}
}

.donut {
	width: 12.5rem;
	height: 12.5rem;
	position: relative;
	margin: auto;
}

.donut__frame,
.donut__circle {
	stroke-width: 0.125rem;
	fill: none;
}

.donut__frame {
	stroke: #ccc;
}

.donut__circle {
	stroke: #000;
	stroke-linecap: round;
}

.donut__canvas {
	width: 100%;
	height: 100%;
	display: block;
	position: relative;
	z-index: 2;
}

.donut__circle {
	transform: rotate(-90deg);
	transform-origin: 50% 50%;
	animation: donut-fill 2s reverse;
}

.donut__circle[stroke-dasharray='0 100'] {
	stroke: none;
}

.donut__text {
	font-family: monospace;
	font-size: 3rem;
	letter-spacing: -0.15rem;
	text-align: center;
	position: absolute;
	top: 50%;
	right: 0;
	left: 0;
	z-index: 3;
	transform: translateY(-50%);
	animation: text-slideup 2s linear;
}

.donut.is--negative .donut__circle {
	transform: rotate(-90deg) scaleY(-1);
}

.donut-complex text {
	font-family: monospace;
	font-size: 1rem;
	font-weight: bold;
	text-shadow: 0 0 0.5rem #fff;
	opacity: 0;
	transition: opacity 0.35s ease-in-out 1s;
}

.donut-complex circle {
	fill: none;
	transition: stroke-dashoffset 1s ease-in-out;
}

.donut-complex:not(.donut-complex--loaded) circle {
	stroke-dashoffset: 0;
}

.donut-complex--loaded text {
	opacity: 1;
}

              
            
!

JS

              
                let rotateAngle = 0;

const SIZE = 34;
const PREFIX = 'donut';

const halfSize = SIZE / 2;
const circleProps = {
	cx: halfSize,
	cy: halfSize,
	r: halfSize - 1
};

const getClassName = (p, c) => `${p}${c}`;
const renderProgress = progress => <strong>{progress}</strong>;

const Donut = ({
	progress = 0,
	onRender = renderProgress,
	prefix = PREFIX
}) => (
	<div className={getClassName(prefix, progress < 0 ? ' is--negative' : '')}>
		<svg
			className={getClassName(prefix, '__canvas')}
			width={SIZE}
			height={SIZE}
			viewBox={`0 0 ${SIZE} ${SIZE}`}
			xmlns="http://www.w3.org/2000/svg"
		>
			<circle
				className={getClassName(prefix, '__frame')}
				{...circleProps}
			/>

			<circle
				className={getClassName(prefix, '__circle')}
				strokeDasharray={`${Math.abs(progress)} 100`}
				{...circleProps}
			/>
		</svg>

		{typeof onRender === 'function' && (
			<div className={getClassName(prefix, '__text')}>
				{onRender(progress)}
			</div>
		)}
	</div>
);

const Donuts = _ => (
	<React.Fragment>
		<Donut progress={0} onRender={renderProgress} />
		<Donut progress={50} onRender={renderProgress} />
		<Donut progress={100} onRender={renderProgress} />
		<Donut progress={-30} onRender={renderProgress} />
	</React.Fragment>
);

class ComplexDonut extends React.Component {
	loadTimeout = 0;

	constructor(props) {
		super(props);

		this.state = {
			total: this.total(props.segments),
			segments: [],
			transforms: this.transforms(),
			isLoaded: false
		};
	}

	total = values => values.reduce((acc, { value }) => acc + value, 0);

	percent = (value, total) => value / total;

	transforms = () => {
		const rotations = [];
		const textCoords = [];
		const { startAngle, segments } = this.props;
		const total = this.total(segments);

		rotateAngle = startAngle;

		this.sortValues(segments).forEach(({ value }) => {
			const data = rotateAngle;
			const percent = this.percent(value, total);
			const { x, y } = this.textCoordinates(value, rotateAngle);

			rotations.push(data);
			textCoords.push({ x, y });

			const result = rotations[rotations.length - 1] || startAngle;

			rotateAngle = percent * 360 + result;
		});

		return { rotations, textCoords };
	};

	sortValues = values => values.sort((a, b) => b.value - a.value);

	circumference = radius => 2 * Math.PI * radius;

	degreesToRadians = angle => angle * (Math.PI / 180);

	strokeDashOffset = (value, circumference) => {
		const diff = this.percent(value, this.state.total) * circumference;
		return circumference - diff;
	};

	textCoordinates = (value, angleOffset) => {
		const { size, radius, segments } = this.props;
		const total = this.total(segments);
		const angle = (this.percent(value, total) * 360) / 2 + angleOffset;
		const radians = this.degreesToRadians(angle);

		return {
			x: radius * Math.cos(radians) + size / 2,
			y: radius * Math.sin(radians) + size / 2
		};
	};

	componentDidMount = () => {
		const { segments, size } = this.props;
		const {
			total,
			transforms: { rotations, textCoords }
		} = this.state;

		this.setState({
			segments: this.sortValues(segments).map(({ value, color }, i) => ({
				value,
				color,
				percent: this.percent(value, total),
				rotate: `rotate(${rotations[i]}, ${size / 2}, ${size / 2})`,
				textCoords: textCoords[i]
			}))
		});

		this.loadTimeout = setTimeout(() => {
			this.setState({
				isLoaded: true
			});
		}, 100);
	};

	componentWillUnmount() {
		this.clearTimeout(this.loadTimeout);
	}

	render() {
		const { size, radius, thickness, className } = this.props;
		const halfSize = size / 2;
		const circumference = this.circumference(radius);

		return (
			<div
				className={`donut-complex${
					this.state.isLoaded ? ' donut-complex--loaded ' : ' '
				}${className}`}
			>
				<svg height={size} width={size} viewBox={`0 0 ${size} ${size}`}>
					{this.state.segments.map((segment, i) => (
						<g key={i}>
							<circle
								r={radius}
								cx={halfSize}
								cy={halfSize}
								transform={segment.rotate}
								stroke={segment.color}
								strokeWidth={thickness}
								strokeDasharray={circumference}
								strokeDashoffset={this.strokeDashOffset(
									segment.value,
									circumference
								)}
							/>
							<text
								x={segment.textCoords.x}
								y={segment.textCoords.y}
								dy="3px"
								textAnchor="middle"
							>
								{`${Math.round(segment.percent * 100)}%`}
							</text>
						</g>
					))}
				</svg>
			</div>
		);
	}
}

ReactDOM.render(<Donuts />, document.getElementById('demo1'));

ReactDOM.render(<ComplexDonut
		size={200}
		radius={80}
		segments={[
			{
				color: '#FF8A80',
				value: 230
			},
			{
				color: '#FF80AB',
				value: 308
			},
			{
				color: '#B9F6CA',
				value: 520
			},
			{
				color: '#B388FF',
				value: 130
			},
			{
				color: '#8C9EFF',
				value: 200
			}
		]}
		thickness={40}
		startAngle={-90}
	/>, document.getElementById('demo2'))

              
            
!
999px

Console