Contour detection

by PhilQ

HTML

<div id="drawing"></div>

<label class="uploadfield">
	<input id="input1" type="file" accept="image/png, image/jpg, image/jpeg">
</label>

SCSS

*, ::before, ::after { margin: 0; padding: 0; box-sizing: border-box; }

body {
	background: #1f2227;
}

#drawing {
	display: block;
}

svg, canvas {
	display: block;
	margin: 50px auto 0;
	background: #1a1d21;
	// background: #fff;
	// background: transparent;
}

.uploadfield {
	position: relative;
	display: flex;
	margin: 50px auto;
	width: 300px;
	height: 80px;
	background: rgba(230, 230, 255, 0.1);
	border-radius: 4px;
	cursor: pointer;
	text-align: center;
	
	&::before {
		content: 'Pick image';
		align-self: center;
		width: 100%;
		padding: 0rem 2rem;
		color: rgba(230, 230, 255, 0.3);
		font-weight: bold;
		font-family: 'Open Sans', sans-serif;
		font-size: 1.5rem;
		text-transform: uppercase;
	}

	input {
		position: absolute;
		opacity: 0;
	}
}

JavaScript

var cnv,
	ctx,
	cnv2,
	ctx2,
	upload,
	imgData = null,
	image_is_loaded = false,
	width = 10,
	height = 10,
	max_width = 800,
	max_height= 1000,
	scale_factor = 1/6
;

const radians = (degrees) => (Math.PI / 180) * degrees;
const degrees = (radians) => radians * (180 / Math.PI);


function handleImage(e) {
	var reader = new FileReader();
	reader.onload = (event) => {
		var img = new Image();
		img.onload = () => {
			// Calculation new dimensions
			let ratio = img.width / img.height;
			let w = max_width;
			let h = max_height;
			if (ratio > 1) {
				h = (max_width / img.width) * img.height;
			} else {
				w = (max_height / img.height) * img.width;
			}
			width = Math.round(w * scale_factor);
			height = Math.round(h * scale_factor);

			// Load image in temporary canvas
			cnv2 = document.createElement('canvas');
			cnv2.width = width;
			cnv2.height = height;
			ctx2 = cnv2.getContext('2d');
			ctx2.drawImage(img, 0, 0, width, height);

			// Get ImageData object and greyscale it
			imgData = ctx2.getImageData(0, 0, width, height);
			imgData = getGreyScaledImageData(imgData);
			ctx2.putImageData(imgData, 0, 0);
			image_is_loaded = true;
			// console.log(imgData);
			
			// Draw on canvas
			width /= scale_factor;
			height /= scale_factor;
			cnv.width = width;
			cnv.height = height;
			// See: https://stackoverflow.com/a/18556117/2142071
			ctx.webkitImageSmoothingEnabled = false;
			ctx.mozImageSmoothingEnabled = false;
			ctx.imageSmoothingEnabled = false;
			ctx.drawImage(cnv2, 0, 0, cnv2.width, cnv2.height, 0, 0, width, height);
			ctx.webkitImageSmoothingEnabled = true;
			ctx.mozImageSmoothingEnabled = true;
			ctx.imageSmoothingEnabled = true;

			processImage();
		}
		img.src = event.target.result;
	}
	reader.readAsDataURL(e.target.files[0]);     
}

function initCanvas() {
	let div = document.getElementById('drawing');
	cnv = document.createElement('canvas');
	cnv.setAttribute('id', 'canvas1');
	div.appendChild(cnv);
	ctx =...