HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by Skypack, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ES6 import
usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<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>
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;
}
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)];
}
Also see: Tab Triggers