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">
-->
<img id="test" src="https://assets.codepen.io/74045/pawel-kadysz-gEMnbCz0Aqw-unsplash.jpg">
<div id="test2"></div>
#test2 img {
max-width: 400px;
max-height: 400px;
}
// Atari 2600 Style Image Converter
// This script converts any image in the DOM to look like Atari 2600 graphics by:
// 1. Reducing the resolution (160x192 max, with chunky "pixels")
// 2. Applying the limited Atari 2600 NTSC color palette (128 colors, with practical limitations)
// 3. Enforcing scanline and sprite-like limitations
// 4. Adding CRT TV effects (optional)
/**
* Convert an image to Atari 2600 graphics style
* @param {string} imageSelector - CSS selector for the source image
* @param {HTMLElement} targetElement - Optional DOM element to render the result to
* @param {Object} options - Optional configuration options
* @returns {Promise<HTMLImageElement>} - The created Atari-style image element
*/
function convertToAtari2600(imageSelector, targetElement = null, options = {}) {
// Set default options
const defaultOptions = {
horizontalResolution: 160, // Atari 2600 max horizontal resolution
scanlineEffect: true, // Add scanlines
crtEffect: true, // Add CRT screen effect
spriteLimitations: true, // Enforce sprite-like limitations per scanline
background: '#000000' // Background color
};
// Merge provided options with defaults
const settings = { ...defaultOptions, ...options };
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";
img.onload = function() {
try {
// Get dimensions
const originalWidth = img.naturalWidth;
const originalHeight = img.naturalHeight;
// Calculate aspect ratio (Atari had ~1:1.2 pixels)
const targetWidth = settings.horizontalResolution;
const targetHeight = Math.floor(originalHeight * (targetWidth / originalWidth));
// Create working canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
canvas.width = targetWidth;
canvas.height = targetHeight;
// Draw image at Atari resolution
ctx.fillStyle = settings.background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
// Get image data
const imageData = ctx.getImageData(0, 0, targetWidth, targetHeight);
const pixels = imageData.data;
// Apply Atari 2600 color palette and limitations
applyAtari2600Limitations(pixels, targetWidth, targetHeight, settings);
// Put processed pixels back
ctx.putImageData(imageData, 0, 0);
// Create the final display canvas (can be larger for better visibility)
const displayScale = Math.min(4, Math.floor(800 / targetWidth));
const displayCanvas = document.createElement('canvas');
const displayCtx = displayCanvas.getContext('2d');
// Set the display size
const displayWidth = targetWidth * displayScale;
const displayHeight = targetHeight * displayScale;
displayCanvas.width = displayWidth;
displayCanvas.height = displayHeight;
// Fill with background color first
displayCtx.fillStyle = settings.background;
displayCtx.fillRect(0, 0, displayWidth, displayHeight);
// Draw scaled image with no smoothing for pixelated look
displayCtx.imageSmoothingEnabled = false;
displayCtx.drawImage(canvas, 0, 0, displayWidth, displayHeight);
// Add CRT effect if enabled
if (settings.crtEffect) {
applyCRTEffect(displayCtx, displayWidth, displayHeight);
}
// Create the Atari-style image
const atariImage = new Image();
atariImage.onload = function() {
// Set basic properties
atariImage.style.width = displayWidth + 'px';
atariImage.style.height = displayHeight + 'px';
atariImage.className = 'atari-2600-image';
atariImage.id = originalImage.id ? originalImage.id + '-atari' : 'atari-2600-image';
atariImage.alt = (originalImage.alt || 'Image') + ' (Atari 2600 Style)';
if (targetElement) {
// If a target element is provided, place the Atari image there
while (targetElement.firstChild) {
targetElement.removeChild(targetElement.firstChild);
}
targetElement.appendChild(atariImage);
} else {
// Otherwise, insert the new image after the original
originalImage.parentNode.insertBefore(atariImage, originalImage.nextSibling);
}
// Resolve the promise with the new image
resolve(atariImage);
};
// Set the source of the Atari image
atariImage.src = displayCanvas.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();
}
});
}
/**
* Apply Atari 2600 color palette and technical limitations to image data
* @param {Uint8ClampedArray} pixels - The pixel data to process
* @param {number} width - Image width
* @param {number} height - Image height
* @param {Object} settings - Configuration settings
*/
function applyAtari2600Limitations(pixels, width, height, settings) {
// Atari 2600 NTSC palette - a subset of the actual palette that was commonly used
// These are the most representative/usable colors from the Atari 2600 NTSC palette
const atariPalette = [
[0, 0, 0], // Black
[64, 64, 64], // Dark Gray
[108, 108, 108], // Light Gray
[255, 255, 255], // White
[152, 34, 32], // Red
[88, 16, 16], // Dark Red
[228, 52, 52], // Bright Red
[111, 44, 0], // Brown
[203, 100, 34], // Orange
[223, 136, 60], // Light Orange
[88, 80, 0], // Dark Green
[146, 144, 0], // Green
[104, 156, 0], // Bright Green
[28, 108, 124], // Teal
[52, 56, 148], // Dark Blue
[100, 100, 224], // Blue
[144, 144, 255], // Light Blue
[120, 28, 128], // Purple
[184, 68, 176], // Magenta
[164, 96, 224] // Lavender
];
// Get background color for this frame - Atari 2600 could only have one background color
// We'll find the most common color in the image for this
const colorCounts = {};
for (let i = 0; i < pixels.length; i += 4) {
if (pixels[i+3] < 128) continue; // Skip transparent pixels
const r = Math.floor(pixels[i] / 32) * 32; // Quantize to reduce unique colors
const g = Math.floor(pixels[i+1] / 32) * 32;
const b = Math.floor(pixels[i+2] / 32) * 32;
const colorKey = `${r},${g},${b}`;
colorCounts[colorKey] = (colorCounts[colorKey] || 0) + 1;
}
// Find the most common color
let backgroundColor = [0, 0, 0]; // Default to black
let maxCount = 0;
for (const colorKey in colorCounts) {
if (colorCounts[colorKey] > maxCount) {
maxCount = colorCounts[colorKey];
backgroundColor = colorKey.split(',').map(Number);
}
}
// Find the closest Atari color to our detected background
const bgAtariColor = findClosestAtariColor(backgroundColor, atariPalette);
// Process each scanline individually to enforce Atari limitations
for (let y = 0; y < height; y++) {
// On Atari 2600, each scanline had very limited sprite capabilities
// We can only have a limited number of different colors per scan line
const lineColors = new Set();
lineColors.add(bgAtariColor.join(',')); // Background is always available
// First pass: identify most important colors in this scanline
const lineColorCounts = {};
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
if (pixels[i+3] < 128) continue; // Skip transparent pixels
const r = pixels[i];
const g = pixels[i+1];
const b = pixels[i+2];
const colorKey = `${r},${g},${b}`;
lineColorCounts[colorKey] = (lineColorCounts[colorKey] || 0) + 1;
}
// Get top colors for this scanline (Atari could have ~3 sprite colors per line)
const topColors = Object.entries(lineColorCounts)
.sort((a, b) => b[1] - a[1])
.slice(0, settings.spriteLimitations ? 3 : 8) // More colors if not enforcing sprite limits
.map(entry => entry[0].split(',').map(Number));
// Map these to closest Atari colors
const scanlineColors = topColors.map(color => {
const atariColor = findClosestAtariColor(color, atariPalette);
return atariColor.join(',');
});
// Add these to our available colors for this scanline
scanlineColors.forEach(color => lineColors.add(color));
// Convert lineColors set back to array of arrays
const availableColors = Array.from(lineColors).map(c => c.split(',').map(Number));
// Second pass: apply the limited colors to this scanline
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
if (pixels[i+3] < 128) {
// For transparent pixels, use background color
pixels[i] = bgAtariColor[0];
pixels[i+1] = bgAtariColor[1];
pixels[i+2] = bgAtariColor[2];
pixels[i+3] = 255;
continue;
}
const pixelColor = [pixels[i], pixels[i+1], pixels[i+2]];
const closestColor = findClosestColor(pixelColor, availableColors);
pixels[i] = closestColor[0];
pixels[i+1] = closestColor[1];
pixels[i+2] = closestColor[2];
// Atari 2600 had consistent full opacity
pixels[i+3] = 255;
// Apply scanline effect (darker every other line)
if (settings.scanlineEffect && y % 2 === 1) {
pixels[i] = Math.max(0, pixels[i] - 30);
pixels[i+1] = Math.max(0, pixels[i+1] - 30);
pixels[i+2] = Math.max(0, pixels[i+2] - 30);
}
}
// Atari 2600 also had a "playfield" which had mirrored left/right halves
// We can simulate this by copying pixels from left to right (for authenticity)
if (settings.spriteLimitations) {
const midpoint = Math.floor(width / 2);
for (let x = 0; x < midpoint; x++) {
// Only mirror certain portions to maintain image recognizability
if (Math.random() < 0.3) { // 30% chance of mirroring any given pixel
const leftIdx = (y * width + x) * 4;
const rightIdx = (y * width + (width - 1 - x)) * 4;
// Copy left to right
pixels[rightIdx] = pixels[leftIdx];
pixels[rightIdx+1] = pixels[leftIdx+1];
pixels[rightIdx+2] = pixels[leftIdx+2];
}
}
}
}
}
/**
* Find the closest color in the Atari 2600 palette to a given color
* @param {Array} color - RGB color to match
* @param {Array} palette - Atari 2600 color palette
* @returns {Array} - The closest Atari color
*/
function findClosestAtariColor(color, palette) {
return findClosestColor(color, palette);
}
/**
* Find the closest color in a palette to a given color
* @param {Array} color - RGB color to match
* @param {Array} palette - Color palette to search
* @returns {Array} - The closest color from the palette
*/
function findClosestColor(color, palette) {
let minDistance = Infinity;
let closestColor = palette[0]; // Default to first color
for (const paletteColor of palette) {
const distance = colorDistance(color, paletteColor);
if (distance < minDistance) {
minDistance = distance;
closestColor = paletteColor;
}
}
return closestColor;
}
/**
* Calculate color distance weighted for human perception
* @param {Array} color1 - First RGB color
* @param {Array} color2 - Second RGB color
* @returns {number} - Perceptual distance between colors
*/
function colorDistance(color1, color2) {
// Use a perceptual color distance formula (weighted Euclidean)
const rMean = (color1[0] + color2[0]) / 2;
const rDiff = color1[0] - color2[0];
const gDiff = color1[1] - color2[1];
const bDiff = color1[2] - color2[2];
// Weights based on human perception
const rWeight = 2 + rMean / 256;
const gWeight = 4.0;
const bWeight = 2 + (255 - rMean) / 256;
return Math.sqrt(
rWeight * rDiff * rDiff +
gWeight * gDiff * gDiff +
bWeight * bDiff * bDiff
);
}
/**
* Apply CRT screen effect to the canvas
* @param {CanvasRenderingContext2D} ctx - Canvas context
* @param {number} width - Canvas width
* @param {number} height - Canvas height
*/
function applyCRTEffect(ctx, width, height) {
// Add TV scanlines
ctx.globalCompositeOperation = 'multiply';
// Add scanlines
for (let y = 0; y < height; y += 2) {
ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
ctx.fillRect(0, y, width, 1);
}
// Add slight screen curvature and CRT glow
ctx.globalCompositeOperation = 'source-over';
// Create radial gradient for CRT effect
const gradient = ctx.createRadialGradient(
width / 2, height / 2, 0,
width / 2, height / 2, width * 0.7
);
gradient.addColorStop(0, 'rgba(255, 255, 255, 0)');
gradient.addColorStop(0.5, 'rgba(30, 30, 30, 0)');
gradient.addColorStop(1, 'rgba(0, 0, 0, 0.4)');
// Apply the gradient
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height);
// Add slight color bleeding (chromatic aberration)
ctx.globalCompositeOperation = 'screen';
ctx.fillStyle = 'rgba(255, 0, 0, 0.03)';
ctx.fillRect(1, 0, width, height);
ctx.fillStyle = 'rgba(0, 0, 255, 0.03)';
ctx.fillRect(-1, 0, width, height);
// Reset composite operation
ctx.globalCompositeOperation = 'source-over';
}
// Usage examples:
// 1. Basic usage with default placement:
// convertToAtari2600('#my-image')
// .then(atariImage => console.log('Conversion complete!'))
// .catch(error => console.error('Error:', error));
//
// 2. With custom target element:
// convertToAtari2600('#my-image', document.getElementById('output-container'))
// .then(atariImage => console.log('Atari conversion rendered to target element'))
// .catch(error => console.error('Error:', error));
//
// 3. With custom options:
// convertToAtari2600('#my-image', document.getElementById('output'), {
// horizontalResolution: 120,
// scanlineEffect: true,
// crtEffect: true,
// spriteLimitations: true,
// background: '#000000'
// })
// .then(atariImage => console.log('Custom Atari conversion complete!'))
// .catch(error => console.error('Error:', error));
convertToAtari2600('#test', document.getElementById('test2'))
.then(atariImage => console.log('Atari conversion rendered to target element'))
.catch(error => console.error('Error:', error));
Also see: Tab Triggers