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 URLs 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 its URL and the proper URL extension.
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 esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM 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="container">
<main>
<div class="content">
<h1>Pixel Sorter</h1>
</div>
<div class="form-control">
<input type="file" accept="image/*" class="js-input-image">
<small>Tip: try uploading a <a href="https://unsplash.com/photos/sf9zGg5DnFw" target="_blank">picture of a landscape</a>.</small>
</div>
<div class="js-output-container" role="presentation"></div>
</main>
<footer class="footer content">
<p>Pixels are sorted by:</p>
<ol>
<li>Light intensity (Y in <a href="https://en.wikipedia.org/wiki/YIQ">YIQ</a> colour space)</li>
<li>Colour intensity (Chroma)</li>
</ol>
</footer>
</div>
$color-brand--primary: #08f;
body {
background-color: #f8f8f8;
color: #222;
line-height: 1.6;
}
:focus {
outline: .125rem solid $color-brand--primary;
}
label {
display: block;
font-weight: bold;
}
input {
display: block;
}
canvas {
display: block;
height: auto !important;
max-width: 100%;
image-rendering: pixelated;
}
a {
color: darken($color-brand--primary, 10%);
&:hover,
&:focus {
color: darken($color-brand--primary, 20%);
}
&:active {
color: darken($color-brand--primary, 30%);
}
}
.container {
max-width: 36em;
margin-left: auto;
margin-right: auto;
}
.form-control {
margin-bottom: 1em;
}
.content {
margin-top: 1em;
margin-bottom: 1em;
}
.content > * {
margin-bottom: 0;
}
.content > :first-child {
margin-top: 0;
}
.content > * + * {
margin-top: 1em;
}
.footer {
font-size: smaller;
}
const shaderSortFragment = `
const vec4 kRGBToYPrime = vec4(0.299, 0.587, 0.114, 0.0);
const vec4 kRGBToI = vec4(0.596, -0.275, -0.321, 0.0);
const vec4 kRGBToQ = vec4(0.212, -0.523, 0.311, 0.0);
// Based on https://github.com/genekogan/Processing-Shader-Examples/blob/master/TextureShaders/data/hue.glsl
vec4 getYIQC(vec4 color) {
float YPrime = dot(color, kRGBToYPrime);
float I = dot(color, kRGBToI);
float Q = dot(color, kRGBToQ);
float chroma = sqrt(I * I + Q * Q);
return vec4(YPrime, I, Q, chroma);
}
// Compare colors by light intensity and color intensity
bool compareColor(vec4 a, vec4 b) {
vec4 aYIQC = getYIQC(a);
vec4 bYIQC = getYIQC(b);
if (aYIQC.x > bYIQC.x) {
return true;
}
if (aYIQC.x == bYIQC.x && aYIQC.w > bYIQC.w) {
return true;
}
return false;
}
uniform float uIteration;
void main() {
vec2 coord = gl_FragCoord.xy;
bool checkPrevious = mod(coord.x + uIteration, 2.0) < 1.0;
vec2 pixel = vec2(-1.0, 0.0) / resolution.xy;
vec2 uv = coord / resolution.xy;
vec4 current = texture2D(uTexture, uv);
vec4 reference = texture2D(uTexture, checkPrevious ? uv - pixel : uv + pixel);
if (checkPrevious) {
if (compareColor(reference, current)) {
gl_FragColor = reference;
return;
}
} else {
if (compareColor(current, reference)) {
gl_FragColor = reference;
return;
}
}
gl_FragColor = current;
}`;
const readFile = (file) => {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.addEventListener('load', () => resolve(reader.result));
reader.readAsDataURL(file);
});
};
const createPlane = () => {
const fragmentShader = `uniform sampler2D uMap;
varying vec2 vUv;
void main() {
gl_FragColor = texture2D(uMap, vUv);
}`;
const vertexShader = `varying vec2 vUv;
void main() {
vUv = uv;
${THREE.ShaderChunk.begin_vertex}
${THREE.ShaderChunk.project_vertex}
}`;
const geometry = new THREE.PlaneGeometry(2, 2, 1, 1);
const material = new THREE.ShaderMaterial({
uniforms: {
uMap: { value: null },
},
fragmentShader,
vertexShader,
});
return new THREE.Mesh(geometry, material);
};
const input = document.querySelector('.js-input-image');
const outputContainer = document.querySelector('.js-output-container');
const gpuComputeTextureSize = 512;
const plane = createPlane();
const camera = new THREE.Camera();
camera.position.z = 1;
const renderer = new THREE.WebGLRenderer({ antialias: false });
renderer.setSize(gpuComputeTextureSize, gpuComputeTextureSize);
const scene = new THREE.Scene();
scene.add(plane);
let gpuCompute,
textureSorted,
variableSorted;
const initGpuCompute = (initialTextureData = null, dispose = false) => {
if (dispose) {
variableSorted.renderTargets.forEach(rt => rt.dispose());
textureSorted.dispose();
}
gpuCompute = new THREE.GPUComputationRenderer(gpuComputeTextureSize, gpuComputeTextureSize, renderer);
textureSorted = gpuCompute.createTexture();
const rowColors = new Array(gpuComputeTextureSize).fill(0).map((n, i) => ({
r: (Math.sin(i) * .124 + 1) / 2,
g: (Math.sin(i + .234) * .563 + 1) / 2,
b: (Math.sin(i + .988) * .348 + 1) / 2,
}));
if (initialTextureData) {
textureSorted.image.data.set(initialTextureData);
} else {
for (let i = 0, channels = 4; i < textureSorted.image.data.length; i += channels) {
const pixelIndex = Math.floor(i / channels);
const y = Math.floor(pixelIndex / gpuComputeTextureSize);
const color = rowColors[(pixelIndex + y * 15838) % rowColors.length];
textureSorted.image.data[i + 0] = color.r;
textureSorted.image.data[i + 1] = color.g;
textureSorted.image.data[i + 2] = color.b;
textureSorted.image.data[i + 3] = 1;
}
}
variableSorted = gpuCompute.addVariable('uTexture', shaderSortFragment, textureSorted);
gpuCompute.setVariableDependencies(variableSorted, [variableSorted]);
const gpuComputeCompileError = gpuCompute.init();
variableSorted.material.uniforms.uIteration = { value: 0 };
if (gpuComputeCompileError !== null) {
console.error(gpuComputeCompileError);
}
};
const getImageData = (image, size = 1) => {
const canvas = document.createElement('canvas');
canvas.height = size;
canvas.width = size;
const context = canvas.getContext('2d');
context.scale(1, -1);
context.drawImage(image, 0, 0, size, -size);
return context.getImageData(0, 0, size, size).data;
};
const animate = (callback) => {
const update = () => {
requestAnimationFrame(update);
callback();
};
update();
};
initGpuCompute();
outputContainer.appendChild(renderer.domElement);
input.addEventListener('change', () => {
const file = input.files[0];
const image = new Image();
if (!file) return;
readFile(file)
.then(dataUrl => new Promise((resolve, reject) => {
image.addEventListener('load', () => resolve())
image.src = dataUrl;
}))
.then(() => {
const textureData = new Float32Array(getImageData(image, gpuComputeTextureSize))
.map(value => value / 256);
initGpuCompute(textureData, true);
});
});
const render = () => {
gpuCompute.compute();
const texture = gpuCompute.getCurrentRenderTarget(variableSorted).texture;
plane.material.uniforms.uMap.value = texture;
variableSorted.material.uniforms.uIteration.value++;
renderer.render(scene, camera);
};
animate(render);
Also see: Tab Triggers