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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

              
                
<div class="wrap">
	<canvas id="canvas"></canvas>
</div>
<div class="item">
	<!--http://oenqoxl4h.bkt.clouddn.com/list05.JPG -->
	<input id="web_pic_url" type="text" value="https://c1.staticflickr.com/1/702/33281887976_1ef29f2397_k.jpg"/>
	<button id="open_web_pic">open</button>
</div>
<div class="item">
	<input type="number" id="K_means" value=5 />
	<button id="census_color">census</button>
</div>
<div class="main_color"><span>main color</span></div>
<div class="average_color"><span>average color</span></div>
<div class="color_wrap"></div>
              
            
!

CSS

              
                html,body{
	padding:0;
	margin:0;
	height:100%;
}
.wrap{
	height:50%;
	background:rgba(140,140,140,0.5);
	text-align:center;
}

#canvas{
	height:100%;
	width: 100%;
	background:#e8e8e8;
}
.color_wrap{
	text-align:center;
}
.color_wrap .color{
	width:35px;
	width:10vw;
	height:35px;
	height:10vw;
	box-sizing:border-box;
	border:1px solid #666;
	display:inline-block;
	margin:10px 0 5px 0;
}
.item{
	margin:10px 5px;
	font-size:0px;
	text-align:center;
}
.item input{
	width:80%;
	height:30px;
	font-size:14px;
	color:#666;
	padding:0 5px;
	margin:0;
	box-sizing:border-box;
}
.item button{
	width: 18%;
	height: 30px;
	margin:0 0 0 2%;
	font-size: 16px;
	background:#E55C5C;
	color:#fff;
	border-radius:4px;
	border:none;
	outline:none;
	-webkit-tap-highlight-color: #999;
	box-sizing:border-box;
}
.main_color,.average_color{
	width:80%;
	height:160px;
	line-height:160px;
	margin: 10px 10%;
	background: #ccc;
	text-align:center;
	font-weight:600;
	font-size: 20px;
	color:#fff;
	transition:all 1000ms ease;
}
              
            
!

JS

              
                class CensusColors {
	constructor(args) {
		args = args || {};
		this.canvas =
			document.querySelector(args.canvas) || document.createElement("canvas");
		this.ctx = this.canvas.getContext("2d");
		this.pixelRatio = window.devicePixelRatio || 1;
		this.hideMode = !document.querySelector(args.canvas);
		this.fre_count = 0;
		// init canvas size
		if (!this.hideMode) {
			this.canvas.width =
				this.pixelRatio * parseInt(getComputedStyle(this.canvas).width);
			this.canvas.height =
				this.pixelRatio * parseInt(getComputedStyle(this.canvas).height);
		}
	}

	drawWebPic(url, callBack) {
		let img = new Image();
		img.crossOrigin = "anonymous";
		let w = this.canvas.width;
		let h = this.canvas.height;
		img.addEventListener("load", () => {
			this.ctx.clearRect(0, 0, w, h); // clear old img
			let scale_x, scale_y;
			if (this.hideMode) {
				scale_x = img.width < window.innerWidth ? 1 : window.innerWidth / img.width;
				scale_y = img.height < window.innerHeight
					? 1
					: window.innerHeight / img.height;
			} else {
				scale_x = img.width < w ? 1 : w / img.width;
				scale_y = img.height < h ? 1 : h / img.height;
			}
			let scale = Math.min(scale_x, scale_y);
			let img_w = img.width * scale;
			let img_h = img.height * scale;
			this.imgWidth = img_w;
			this.imgHeight = img_h;
			if (this.hideMode) {
				this.canvas.width = img_w;
				this.canvas.height = img_h;
				this.ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, img_w, img_h);
			} else {
				this.ctx.drawImage(
					img,
					0,
					0,
					img.width,
					img.height,
					(w - img_w) / 2,
					(h - img_h) / 2,
					img_w,
					img_h
				);
			}
			if (callBack instanceof Function) {
				callBack(img);
			}
		});
		img.src = url;
	}

	censusColors(K, callBack) {
		if (!this.imgWidth || !this.imgHeight) {
			console.log("did not find image!");
			return;
		}
		let start = +new Date();
		let w = this.canvas.width;
		let h = this.canvas.height;
		let img_w = this.imgWidth;
		let img_h = this.imgHeight;
		let step = img_w * img_h < 500 * 500
			? this.pixelRatio > 1 ? 6 : 5
			: this.pixelRatio > 1 ? 10 : 8;
		console.log("step: " + step);
		let imageDate = this.ctx.getImageData(
			(w - img_w) / 2,
			(h - img_h) / 2,
			img_w,
			img_h
		);
		if (!imageDate) {
			console.log(
				"can not read image data, maybe because of cross-domain limitation."
			);
			return;
		}
		let rows = imageDate.height;
		let cols = imageDate.width;
		let rgb_key = [];
		let colors_info = [];
		let r_one, g_one, b_one, r, g, b;
		this.fre_count = 0;
		for (let row = 1; row < rows - 1; ) {
			for (let col = 1; col < cols - 1; ) {
				this.fre_count++;
				r = imageDate.data[row * cols * 4 + col * 4];
				g = imageDate.data[row * cols * 4 + col * 4 + 1];
				b = imageDate.data[row * cols * 4 + col * 4 + 2];
				r_one = Math.floor(r / 10) * 1000000;
				g_one = Math.floor(g / 10) * 1000;
				b_one = Math.floor(b / 10);
				let key = r_one + g_one + b_one;
				let index = rgb_key.indexOf(key);
				if (index < 0) {
					rgb_key.push(key);
					let hsl = rgbToHsl(r, g, b);
					colors_info.push({
						key: key,
						fre: 1,
						r: r,
						g: g,
						b: b,
						h: hsl[0],
						s: hsl[1],
						l: hsl[2],
						category: -1
					});
				} else {
					colors_info[index].fre++;
				}
				col += step;
			}
			row += step;
		}

		// filter and sort rgb_census
		let len = rgb_key.length;
		console.log("found colors: ", len);
		console.log("fre count: " + this.fre_count);
		let thd = 0.85;
		console.log("thd: " + thd);
		let count = 0;
		let count_total = this.fre_count;
		colors_info = colors_info.filter(color => {
			count += color.fre;
			return count / count_total < thd;
		});
		len = colors_info.length;
		console.log("after filter colors: ", len);
		console.log(colors_info);

		colors_info.sort(function(pre, next) {
			return next.fre - pre.fre;
		});
		console.log("time: ", +new Date() - start);
		// k-mean clustering
		start = +new Date();
		let init_seed = [];
		for (let i = 0; i < len; i++) {
			let l = init_seed.length;
			if (!i) {
				init_seed.push({
					h: colors_info[i].h,
					s: colors_info[i].s,
					l: colors_info[i].l
				});
				colors_info[i].category = 0;
				continue;
			}
			let j = 0;
			for (; j < l; j++) {
				let h_diff = Math.abs(init_seed[j].h - colors_info[i].h);
				let s_diff = Math.abs(init_seed[j].s - colors_info[i].s);
				let l_diff = Math.abs(init_seed[j].l - colors_info[i].l);
				if (h_diff < 15 && s_diff < 15 && l_diff < 15) {
					break;
				}
			}
			if (j === l) {
				init_seed.push({
					h: colors_info[i].h,
					s: colors_info[i].s,
					l: colors_info[i].l
				});
				colors_info[i].category = init_seed.length - 1;
			}
			if (init_seed.length >= K) {
				break;
			}
		}
		console.log("init_seed: ");
		console.log(init_seed);
		let cluster_res = this.kMC(colors_info, init_seed, 100);
		console.log("time: ", +new Date() - start);
		if (callBack instanceof Function) {
			callBack(colors_info, cluster_res);
		}
	}

	kMC(colors, seeds, max_step) {
		let iteration_count = 0;

		while (iteration_count++ < max_step) {
			console.log("KMC iteration " + iteration_count);
			// filter seeds
			seeds = seeds.filter(seed => {
				return seed;
			});
			// divide colors into different categories with duff's device
			let len = colors.length;
			let count = (len / 8) ^ 0;
			let start = len % 8;
			while (start--) {
				this.classifyColor(colors[start], seeds);
			}
			while (count--) {
				this.classifyColor(colors[--len], seeds);
				this.classifyColor(colors[--len], seeds);
				this.classifyColor(colors[--len], seeds);
				this.classifyColor(colors[--len], seeds);
				this.classifyColor(colors[--len], seeds);
				this.classifyColor(colors[--len], seeds);
				this.classifyColor(colors[--len], seeds);
				this.classifyColor(colors[--len], seeds);
			}

			// compute center of category
			len = colors.length;
			let hsl_count = [];
			let category;
			while (len--) {
				category = colors[len].category;
				if (!hsl_count[category]) {
					hsl_count[category] = {};
					hsl_count[category].h = 0;
					hsl_count[category].s = 0;
					hsl_count[category].l = 0;
					hsl_count[category].fre_count = colors[len].fre;
				} else {
					hsl_count[category].fre_count += colors[len].fre;
				}
			}
			len = colors.length;
			while (len--) {
				category = colors[len].category;
				hsl_count[category].h +=
					colors[len].h * colors[len].fre / hsl_count[category].fre_count;
				hsl_count[category].s +=
					colors[len].s * colors[len].fre / hsl_count[category].fre_count;
				hsl_count[category].l +=
					colors[len].l * colors[len].fre / hsl_count[category].fre_count;
			}
			let flag = hsl_count.every((ele, index) => {
				return (
					Math.abs(ele.h - seeds[index].h) < 0.5 &&
					Math.abs(ele.s - seeds[index].s) < 0.5 &&
					Math.abs(ele.l - seeds[index].l) < 0.5
				);
			});
			seeds = hsl_count.map((ele, index) => {
				return {
					h: ele.h,
					s: ele.s,
					l: ele.l
				};
			});
			console.log("new category: ");
			console.log(seeds);
			if (flag) {
				break;
			}
		}
		return seeds;
	}

	classifyColor(color, classes) {
		let len = classes.length;
		let min = 10000;
		let min_index;
		while (len--) {
			let distance =
				Math.abs(classes[len].h - color.h) +
				Math.abs(classes[len].s - color.s) +
				Math.abs(classes[len].l - color.l);
			if (distance < min) {
				min = distance;
				min_index = len;
			}
		}
		color.category = min_index;
	}
}

var censusColors = new CensusColors({
	canvas: "#canvas"
});

document.querySelector("#open_web_pic").onclick = function() {
	let img_src = document.querySelector("#web_pic_url").value;
	if (img_src) {
		censusColors.drawWebPic(img_src, function(img) {
			console.log("load img: " + img.src);
			console.log("img width is: " + img.width);
			console.log("img height is: " + img.height);
		});
	}
};
document.querySelector("#census_color").onclick = function() {
	censusColors.censusColors(
		document.querySelector("#K_means").value,
		(colors, clusters) => {
			// set main color
			document.querySelector(".main_color").style.background =
				"rgb(" + colors[0].r + "," + colors[0].g + "," + colors[0].b + ")";

			// compute average color
			let len = colors.length;
			let r_count = 0,
				g_count = 0,
				b_count = 0,
				fre_count = 0;
			while (len--) {
				r_count += colors[len].r * colors[len].fre;
				g_count += colors[len].g * colors[len].fre;
				b_count += colors[len].b * colors[len].fre;
				fre_count += colors[len].fre;
			}
			document.querySelector(".average_color").style.background =
				"rgb(" +
				Math.floor(r_count / fre_count) +
				"," +
				Math.floor(g_count / fre_count) +
				"," +
				Math.floor(b_count / fre_count) +
				")";

			len = -1;
			let color_wrap = document.createDocumentFragment();
			while (++len < clusters.length) {
				let rgb = hslToRgb(clusters[len].h, clusters[len].s, clusters[len].l);
				let div = document.createElement("div");
				div.classList.add("color");
				div.style.background = "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")";
				color_wrap.appendChild(div);
			}
			document.querySelector(".color_wrap").appendChild(color_wrap);
		}
	);
};

function rgbToHsl(r, g, b) {
	(r /= 255), (g /= 255), (b /= 255);
	var max = Math.max(r, g, b),
		min = Math.min(r, g, b);
	var h,
		s,
		l = (max + min) / 2;

	if (max == min) {
		h = s = 0; // achromatic
	} else {
		var d = max - min;
		s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
		switch (max) {
			case r:
				h = (g - b) / d + (g < b ? 6 : 0);
				break;
			case g:
				h = (b - r) / d + 2;
				break;
			case b:
				h = (r - g) / d + 4;
				break;
		}
		h *= 60;
	}

	return [h, s * 100, l * 100];
}

function hslToRgb(h, s, l) {
	h = h / 360;
	s = s / 100;
	l = l / 100;
	var r, g, b;

	if (s == 0) {
		r = g = b = l; // achromatic
	} else {
		var hue2rgb = function hue2rgb(p, q, t) {
			if (t < 0) t += 1;
			if (t > 1) t -= 1;
			if (t < 1 / 6) return p + (q - p) * 6 * t;
			if (t < 1 / 2) return q;
			if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
			return p;
		};

		var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
		var p = 2 * l - q;
		r = hue2rgb(p, q, h + 1 / 3);
		g = hue2rgb(p, q, h);
		b = hue2rgb(p, q, h - 1 / 3);
	}
	return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}

              
            
!
999px

Console