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

              
                <main class="container">
	<h1>Genetic Algorithm to Recreate an Image Using Shapes</h1>
	
	<div class="preview-list">
		<div class="preview-list__item" data-ref="preview"></div>
		<div class="preview-list__item" data-ref="target"></div>
	</div>
	
	<dl>
		<div>
			<dt>Generation</dt>
			<dd data-ref="generation"></dd>
		</div>
		
		<div>
			<dt>Accuracy</dt>
			<dd data-ref="highscore"></dd>
		</div>
		
		<div>
			<dt>Mutation rate</dt>
			<dd data-ref="mutation-rate"></dd>
		</div>
	</dl>
</main>
              
            
!

CSS

              
                canvas {
	display: block;
}

dl {
	display: flex;
	flex-direction: row;
}

dl > div {
	margin-right: 1rem;
}

dt {
	font-weight: bold;
}
dd {
	margin-left: 0;
	margin-bottom: 1rem;
	font-family: monospace;
}

h1 {
	margin-bottom: 1rem;
	margin-top: 0;
}

img {
	display: block;
}

.container {
	margin: 1rem;
}

.preview-list {
	display: flex;
	flex-direction: row;
}
.preview-list__item {
	padding: 0.5rem;
}
              
            
!

JS

              
                const CanvasContextFactory = {
	createContext(width, height) {
		const canvas = document.createElement('canvas');
		
		canvas.height = height;
		canvas.width = width;
		
		return canvas.getContext('2d');
	},
	
	createContextFromImage(image, size) {
		const aspect = image.width / image.height;
		const context = aspect > 1
			? CanvasContextFactory.createContext(size, size / aspect)
			: CanvasContextFactory.createContext(size / aspect, size);
		
		const { height, width } = context.canvas;
		
		context.fillRect(0, 0, width, height);
		context.drawImage(image, 0, 0, width, height);
		
		return context;
	},
	
	createContextFromImageGrayscale(image, size) {
		const context = this.createContextFromImage(image, size);

		const { height, width } = context.canvas;
		const imageData = context.getImageData(0, 0, width, height);
		
		for (let pixelIndex = 0; pixelIndex < width * height; pixelIndex++) {
			const dataIndex = 4 * pixelIndex;
			const luma = ImageDataAnalyzer.getLuma(
				imageData.data[dataIndex + 0],
				imageData.data[dataIndex + 1],
				imageData.data[dataIndex + 2]
			);
			
			imageData.data[dataIndex + 0] = luma;
			imageData.data[dataIndex + 1] = luma;
			imageData.data[dataIndex + 2] = luma;
		}
		
		context.putImageData(imageData, 0, 0);
		
		return context;
	}
};

const ImageDataAnalyzer = {
	getDifference(a, b) {
		const { height, width } = a;
		let difference = 0;
		
		for (let pixelIndex = 0; pixelIndex < width * height; pixelIndex++) {
			const dataIndex = 4 * pixelIndex;
			
			difference += (
				Math.abs(a.data[dataIndex + 0] - b.data[dataIndex + 0]) +
				Math.abs(a.data[dataIndex + 1] - b.data[dataIndex + 1]) +
				Math.abs(a.data[dataIndex + 2] - b.data[dataIndex + 2])
			);
		}
		
		return difference / (width * height * 3 * 255);
	},
	
	getDifferenceGrayscale(a, b) {
		const { height, width } = a;
		let difference = 0;
		
		for (let pixelIndex = 0; pixelIndex < width * height; pixelIndex++) {
			const dataIndex = 4 * pixelIndex;
			
			difference += Math.abs(a.data[dataIndex + 0] - b.data[dataIndex + 0]);
		}
		
		return difference / (width * height * 255);
	},
	
	getLuma(r, g, b) {
		return r * 0.2126 + g * 0.7152 + b * 0.0722;
	},
};

const ImageLoader = {
	load(source) {
		return new Promise((resolve) => {
			const image = new Image();
			
			image.crossOrigin = 'anonymous';
			image.addEventListener('load', () => resolve(image));
			image.src = source;
		});
	},
};

const MathUtils = {
	lerp(a, b, t) {
		return a + t * (b - a);
	},
};

class Circle {
	constructor(
		x = Circle.getRandomX(),
	  y = Circle.getRandomY(),
		z = Circle.getRandomZ(),
		radius = Circle.getRandomRadius(),
		color = Circle.getRandomColor(),
	) {
		this.color = Math.max(0, Math.min(1, color));
		this.colorParsed = Circle.decimalToColor(this.color);
			
		this.radius = radius;
		this.x = x;
		this.y = y;
	}
	
	render(context) {
		const { height, width } = context.canvas;
		const sizeHalf = 0.5 * Math.min(height, width);
		
		context.beginPath();
		context.arc(width * this.x, width * this.y, sizeHalf * this.radius, 0, 2 * Math.PI);
		context.fillStyle = this.colorParsed;
		
		context.fill();
	}
	
	static decimalToColor(decimal) {
		// const hex = Math.floor((0xFFFFFF + 1) * decimal).toString(16).padStart(6, '0');
		
		// return `#${hex}`;
		
		return `hsl(0, 0%, ${100 * decimal}%)`;
	}
	
	static getRandomX() {
		return Math.random();
	}
	
	static getRandomY() {
		return Math.random();
	}
	
	static getRandomZ() {
		return Math.random();
	}
	
	static getRandomRadius() {
		return Math.random();
	}
	
	static getRandomColor() {
		return Math.random();
	}
}

class Organism {
	constructor(circles = Organism.getRandomCircles()) {
		this.circles = circles.sort((a, b) => b.z - a.z);
		this.score = null;
	}
	
	render(context) {
		const { height, width } = context.canvas;
		
		context.fillRect(0, 0, width, height);
		this.circles.forEach(c => c.render(context));
	}
	
	static get CIRCLE_COUNT() {
		return 64;
	}
	
	static getRandomCircles() {
		return Array.from({ length: Organism.CIRCLE_COUNT }, () => new Circle());
	}
}

class Population {
	constructor(size, targetContext) {
		if (size % 2 === 1) {
			throw new Error('This algorithm simulates cellular division to optimize. Please use an even population size.');
		}
		
		const { height, width } = targetContext.canvas;
		
		this.context = CanvasContextFactory.createContext(width, height);
		this.mutationRate = 0.1;
		this.organismList = Array.from({ length: size }, () => new Organism());
		this.populationSize = size;
		this.targetContext = targetContext;
		this.targetImageData = targetContext.getImageData(0, 0, width, height);
	}
	
	createNextPopulation(parents) {
		const organismList = this._getOrganismResultList();
		// const organismElite = this._getOrganismResultList();
		
		this.organismList = [
			...organismList,
			...organismList.map(parent => new Organism(parent.circles.map(circle => new Circle(
				Math.random() < this.mutationRate ? Circle.getRandomX() : circle.x,
				Math.random() < this.mutationRate ? Circle.getRandomY() : circle.y,
				Math.random() < this.mutationRate ? Circle.getRandomZ() : circle.z,
				Math.random() < this.mutationRate ? Circle.getRandomRadius() : circle.radius,
				Math.random() < this.mutationRate ? Circle.getRandomColor() : circle.color,
			))))
			
// 			organismElite,

// 			...Array.from({ length: this.organismList.length - 1 }, () => {
// 				return new Organism(organismElite.circles.map(circle => new Circle(
// 					Math.random() < this.mutationRate ? Circle.getRandomX() : circle.x,
// 					Math.random() < this.mutationRate ? Circle.getRandomY() : circle.y,
// 					Math.random() < this.mutationRate ? Circle.getRandomZ() : circle.z,
// 					Math.random() < this.mutationRate ? Circle.getRandomRadius() : circle.radius,
// 					Math.random() < this.mutationRate ? Circle.getRandomColor() : circle.color,
// 				)));
// 			}),
		];
		
		return this.organismList[0];
	}
	
	_getOrganismResultList(targetImageData) {
		const { height, width } = this.targetContext.canvas;
		
		this.organismList.forEach((organism) => {
			if (organism.score !== null) return;
			
			organism.render(this.context);
			
			const imageData = this.context.getImageData(0, 0, width, height);
			const score = 1 - ImageDataAnalyzer.getDifferenceGrayscale(this.targetImageData, imageData);
			
			organism.score = score;
		});
		
		return Array.from(this.organismList)
			.sort((a, b) => b.score - a.score)
			// .shift();
			.slice(0, 0.5 * this.organismList.length);
	}
}

const createAnimationLoop = (callback) => {
	let frame = 0;

	const update = () => {
		requestAnimationFrame(update);
		callback(frame++);
	};
	
	requestAnimationFrame(update);
};

const URL_IMAGE = 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/67/Firefox_Logo%2C_2017.svg/1024px-Firefox_Logo%2C_2017.svg.png';

const elementGeneration = document.querySelector('[data-ref="generation"]');
const elementHighscore = document.querySelector('[data-ref="highscore"]');
const elementMutationRate = document.querySelector('[data-ref="mutation-rate"]');

(async () => {
	const image = await ImageLoader.load(URL_IMAGE);
	const contextImage = CanvasContextFactory.createContextFromImageGrayscale(image, 128);
	const contextPreview = CanvasContextFactory.createContext(
		contextImage.canvas.width,
		contextImage.canvas.height);
	
	const population = new Population(16, contextImage);
	let result;
	
	document.querySelector('[data-ref="preview"]').appendChild(contextImage.canvas);
	document.querySelector('[data-ref="target"]').appendChild(contextPreview.canvas);
	
	createAnimationLoop((frame) => {
		const organism = population.createNextPopulation();
		
		organism.render(contextPreview);
		population.mutationRate = MathUtils.lerp(0.5, 0.2, Math.pow(organism.score, 2));
		
		elementGeneration.textContent = frame;
		elementHighscore.textContent = organism.score.toFixed(10);
		elementMutationRate.textContent = population.mutationRate;
	});
})();

              
            
!
999px

Console