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.
<img id="test" src="https://unsplash.it/640/425?image=40">
<div id="test2"></div>
#test2 img {
max-width: 400px;
max-height: 400px;
}
// Image to Pixel Art Converter
// This script converts any image in the DOM to pixel art by:
// 1. Reducing the resolution (creating larger "pixels")
// 2. Reducing the color palette
// 3. Rendering the result either to a new DOM element or a specified target element
/**
* Convert an image to pixel art
* @param {string} imageSelector - CSS selector for the source image
* @param {number} pixelSize - Size of each "pixel" block (higher = more blocky)
* @param {number} colorCount - Number of colors in the reduced palette
* @param {HTMLElement} targetElement - Optional DOM element to render the result to
* @returns {Promise<HTMLImageElement>} - The created pixel art image element
*/
function convertToPixelArt(imageSelector, pixelSize = 8, colorCount = 16, targetElement = null) {
return new Promise((resolve, reject) => {
// Get the image from the DOM
const originalImage = document.querySelector(imageSelector);
if (!originalImage) {
const error = new Error(`Image not found with selector: ${imageSelector}`);
console.error(error);
reject(error);
return;
}
// Create a new image element to ensure the original image is fully loaded
const img = new Image();
img.crossOrigin = "Anonymous"; // Handle cross-origin issues if needed
// Set up onload handler before setting src
img.onload = function() {
try {
// Create canvas elements for processing
const smallCanvas = document.createElement('canvas');
const smallCtx = smallCanvas.getContext('2d', { willReadFrequently: true });
const finalCanvas = document.createElement('canvas');
const finalCtx = finalCanvas.getContext('2d', { willReadFrequently: true });
// Calculate dimensions
const width = img.naturalWidth;
const height = img.naturalHeight;
// Calculate the reduced size for pixelation
const smallWidth = Math.max(1, Math.floor(width / pixelSize));
const smallHeight = Math.max(1, Math.floor(height / pixelSize));
// Step 1: Reduce the image resolution
smallCanvas.width = smallWidth;
smallCanvas.height = smallHeight;
smallCtx.drawImage(img, 0, 0, smallWidth, smallHeight);
// Step 2: Get the pixel data and reduce colors
const imageData = smallCtx.getImageData(0, 0, smallWidth, smallHeight);
const reducedPixels = reduceColors(imageData.data, colorCount);
// Create new ImageData to hold our reduced-color image
const reducedImageData = new ImageData(
new Uint8ClampedArray(reducedPixels),
smallWidth,
smallHeight
);
smallCtx.putImageData(reducedImageData, 0, 0);
// Step 3: Scale it back up with pixelated rendering
finalCanvas.width = width;
finalCanvas.height = height;
finalCtx.imageSmoothingEnabled = false; // Critical for pixelated look
finalCtx.drawImage(
smallCanvas,
0, 0, smallWidth, smallHeight,
0, 0, width, height
);
// Create the pixel art image
const pixelArtImage = new Image();
pixelArtImage.onload = function() {
// Set basic properties
pixelArtImage.style.width = width + 'px';
pixelArtImage.style.height = height + 'px';
pixelArtImage.className = 'pixel-art';
pixelArtImage.id = originalImage.id ? originalImage.id + '-pixel' : 'pixel-art-image';
pixelArtImage.alt = (originalImage.alt || 'Image') + ' (Pixel Art)';
if (targetElement) {
// If a target element is provided, place the pixel art image there
while (targetElement.firstChild) {
targetElement.removeChild(targetElement.firstChild);
}
targetElement.appendChild(pixelArtImage);
} else {
// Otherwise, insert the new image after the original
originalImage.parentNode.insertBefore(pixelArtImage, originalImage.nextSibling);
}
// Resolve the promise with the new image
resolve(pixelArtImage);
};
// Set the source of the pixel art image
pixelArtImage.src = finalCanvas.toDataURL('image/png');
} catch (error) {
console.error('Error processing image:', error);
reject(error);
}
};
// Handle image loading errors
img.onerror = function(error) {
console.error('Error loading image:', error);
reject(new Error('Failed to load the image'));
};
// Start loading the image
img.src = originalImage.src;
// If the image is already loaded in cache, manually trigger the onload
if (img.complete) {
img.onload();
}
});
}
/**
* Function to reduce the number of colors in the image
* @param {Uint8ClampedArray} pixels - The pixel data from canvas
* @param {number} colorCount - Number of colors to reduce to
* @returns {Uint8ClampedArray} - Processed pixel data with reduced colors
*/
function reduceColors(pixels, colorCount) {
// Create a copy of the pixels array to avoid modifying the original
const result = new Uint8ClampedArray(pixels.length);
// Extract RGB values from non-transparent pixels
const rgbValues = [];
for (let i = 0; i < pixels.length; i += 4) {
if (pixels[i+3] > 128) { // Only consider pixels that aren't very transparent
rgbValues.push({
index: i,
color: [pixels[i], pixels[i+1], pixels[i+2]]
});
}
// Copy alpha channel directly
result[i+3] = pixels[i+3];
}
// If we don't have enough pixels, return the original
if (rgbValues.length <= colorCount) {
return pixels;
}
// Get a color palette using median cut algorithm
const palette = medianCut(rgbValues.map(p => p.color), colorCount);
// Map each pixel to its closest color in the palette
for (let i = 0; i < pixels.length; i += 4) {
// Skip fully transparent pixels
if (pixels[i+3] < 128) {
result[i] = 0;
result[i+1] = 0;
result[i+2] = 0;
continue;
}
const pixelColor = [pixels[i], pixels[i+1], pixels[i+2]];
const closestColor = findClosestColor(pixelColor, palette);
result[i] = closestColor[0]; // R
result[i+1] = closestColor[1]; // G
result[i+2] = closestColor[2]; // B
}
return result;
}
/**
* Simple implementation of median cut algorithm for color quantization
* @param {Array} colors - Array of RGB color arrays
* @param {number} colorCount - Number of colors to reduce to
* @returns {Array} - Array of representative colors (the palette)
*/
function medianCut(colors, colorCount) {
// Start with one bucket containing all colors
let buckets = [{
colors: colors
}];
// Split buckets until we have enough
while (buckets.length < colorCount) {
// Find the bucket with the largest range
let bucketToSplit = 0;
let maxRange = 0;
for (let i = 0; i < buckets.length; i++) {
const bucket = buckets[i];
if (!bucket.range) {
// Calculate color ranges for this bucket
const ranges = [0, 0, 0]; // R, G, B ranges
for (let j = 0; j < 3; j++) {
let min = 255;
let max = 0;
for (const color of bucket.colors) {
if (color[j] < min) min = color[j];
if (color[j] > max) max = color[j];
}
ranges[j] = max - min;
}
// Store the maximum range and its channel
bucket.range = Math.max(...ranges);
bucket.rangeChannel = ranges.indexOf(bucket.range);
}
if (bucket.range > maxRange) {
maxRange = bucket.range;
bucketToSplit = i;
}
}
// If no good split is found, break
if (maxRange === 0) break;
// Split the chosen bucket
const bucket = buckets[bucketToSplit];
const channel = bucket.rangeChannel;
// Sort colors by the chosen channel
bucket.colors.sort((a, b) => a[channel] - b[channel]);
// Find median point
const medianIndex = Math.floor(bucket.colors.length / 2);
// Create two new buckets
buckets.splice(bucketToSplit, 1,
{ colors: bucket.colors.slice(0, medianIndex) },
{ colors: bucket.colors.slice(medianIndex) }
);
}
// Calculate the average color for each bucket
return buckets.map(bucket => {
if (bucket.colors.length === 0) {
return [0, 0, 0]; // Default to black if empty
}
const sum = [0, 0, 0];
for (const color of bucket.colors) {
sum[0] += color[0];
sum[1] += color[1];
sum[2] += color[2];
}
return [
Math.round(sum[0] / bucket.colors.length),
Math.round(sum[1] / bucket.colors.length),
Math.round(sum[2] / bucket.colors.length)
];
});
}
/**
* Find the closest color in the palette to a pixel
* @param {Array} pixel - RGB array of the pixel color
* @param {Array} palette - Array of RGB arrays for the color palette
* @returns {Array} - The closest color from the palette
*/
function findClosestColor(pixel, palette) {
let minDistance = Infinity;
let closestColor = null;
for (const color of palette) {
const distance = colorDistance(pixel, color);
if (distance < minDistance) {
minDistance = distance;
closestColor = color;
}
}
return closestColor;
}
/**
* Calculate the color distance (weighted Euclidean distance in RGB space)
* @param {Array} color1 - First RGB color array
* @param {Array} color2 - Second RGB color array
* @returns {number} - Distance between the colors
*/
function colorDistance(color1, color2) {
// Weighted RGB distance - human eyes are more sensitive to green
const rDiff = color1[0] - color2[0];
const gDiff = color1[1] - color2[1];
const bDiff = color1[2] - color2[2];
return Math.sqrt(0.3 * rDiff * rDiff + 0.59 * gDiff * gDiff + 0.11 * bDiff * bDiff);
}
// Usage examples:
// 1. Basic usage with default placement:
// convertToPixelArt('#my-image', 8, 16)
// .then(pixelArtImage => console.log('Conversion complete!'))
// .catch(error => console.error('Error:', error));
//
// 2. With custom target element:
// convertToPixelArt('#my-image', 8, 16, document.getElementById('output-container'))
// .then(pixelArtImage => console.log('Pixel art rendered to target element'))
// .catch(error => console.error('Error:', error));
convertToPixelArt('#test', 8, 16, document.querySelector('#test2'))
.then(pixelArtImage => console.log('Pixel art rendered to target element'))
.catch(error => console.error('Error:', error));
console.log('done');
Also see: Tab Triggers