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="app-container">
<div class="container">
<aside class="sidebar">
<!-- Upload Section -->
<div class="panel upload-panel">
<div class="upload-area">
<label for="fileUpload" class="upload-label">
<span class="upload-icon">📁</span>
<span>Drop image/video or click to upload</span>
</label>
<input type="file" id="fileUpload" accept="image/*,video/*" class="upload-input">
</div>
</div>
<!-- Controls Section -->
<div class="panel controls-panel">
<!-- Primary Controls -->
<div class="control-group">
<label for="gridSize">Grid Size</label>
<div class="slider-container">
<input type="range" id="gridSize" min="5" max="50" value="20">
<span class="value-display" id="gridSizeVal">20</span>
</div>
</div>
<!-- Image Adjustments -->
<div class="control-section">
<h3>Image Adjustments</h3>
<div class="control-group">
<label for="brightness">Brightness</label>
<div class="slider-container">
<input type="range" id="brightness" min="-100" max="100" value="20">
<span class="value-display" id="brightnessVal">20</span>
</div>
</div>
<div class="control-group">
<label for="contrast">Contrast</label>
<div class="slider-container">
<input type="range" id="contrast" min="-100" max="100" value="0">
<span class="value-display" id="contrastVal">0</span>
</div>
</div>
<div class="control-group">
<label for="gamma">Gamma</label>
<div class="slider-container">
<input type="range" id="gamma" min="0.1" max="3" step="0.1" value="1.0">
<span class="value-display" id="gammaVal">1.0</span>
</div>
</div>
<div class="control-group">
<label for="smoothing">Smoothing</label>
<div class="slider-container">
<input type="range" id="smoothing" min="0" max="5" step="0.5" value="0">
<span class="value-display" id="smoothingVal">0</span>
</div>
</div>
</div>
<!-- Dithering Options -->
<div class="control-section">
<h3>Dithering</h3>
<div class="control-group">
<select id="ditherType" class="dither-select">
<option value="FloydSteinberg">Smooth Transition (Floyd‑Steinberg)</option>
<option value="Ordered">Patterned Look (Ordered)</option>
<option value="Noise">Grainy Texture (Noise)</option>
<option value="None" selected>No Extra Texture</option>
</select>
</div>
</div>
</div>
<!-- Action Buttons -->
<div class="panel action-panel">
<button id="resetButton" class="btn btn-secondary">Reset All</button>
<button id="saveButton" class="btn btn-primary">Export PNG</button>
</div>
</aside>
<main class="main-content">
<div class="canvas-container">
<canvas id="halftoneCanvas"></canvas>
</div>
</main>
</div>
</div>
:root {
--primary-color: #2196F3;
--primary-dark: #1976D2;
--secondary-color: #757575;
--background-color: #f8f8f8;
--panel-background: #ffffff;
--text-color: #333333;
--border-radius: 8px;
--spacing-unit: 16px;
--shadow: 0 1px 2px rgba(0,0,0,0.1);
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: var(--background-color);
color: var(--text-color);
margin: 0;
padding: 0;
min-height: 100vh;
}
.app-container {
max-width: 1440px;
margin: 0 auto;
padding: var(--spacing-unit);
}
.container {
display: flex;
gap: calc(var(--spacing-unit) * 2);
}
/* Sidebar Styles */
.sidebar {
width: 320px;
flex-shrink: 0;
}
.panel {
background: var(--panel-background);
border-radius: var(--border-radius);
padding: var(--spacing-unit);
margin-bottom: var(--spacing-unit);
box-shadow: var(--shadow);
}
.panel h3 {
font-size: 14px;
text-transform: uppercase;
color: var(--secondary-color);
margin: calc(var(--spacing-unit) * 1.5) 0 var(--spacing-unit) 0;
letter-spacing: 0.5px;
}
/* Upload Area Styles */
.upload-area {
border: 2px dashed #e0e0e0;
border-radius: var(--border-radius);
padding: calc(var(--spacing-unit) * 1.5);
text-align: center;
transition: all 0.3s ease;
}
.upload-area:hover {
border-color: var(--primary-color);
background-color: rgba(33, 150, 243, 0.05);
}
.upload-label {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
cursor: pointer;
color: var(--secondary-color);
}
.upload-icon {
font-size: 24px;
}
.upload-input {
display: none;
}
/* Control Groups */
.control-group {
margin-bottom: var(--spacing-unit);
}
.control-group label {
display: block;
margin-bottom: 8px;
font-weight: 500;
font-size: 14px;
}
.slider-container {
display: flex;
align-items: center;
gap: 12px;
}
input[type="range"] {
flex: 1;
height: 4px;
-webkit-appearance: none;
background: #e0e0e0;
border-radius: 2px;
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 16px;
height: 16px;
background: var(--primary-color);
border-radius: 50%;
cursor: pointer;
transition: all 0.2s ease;
}
input[type="range"]::-webkit-slider-thumb:hover {
transform: scale(1.1);
}
.value-display {
min-width: 40px;
text-align: right;
font-size: 14px;
color: var(--secondary-color);
}
/* Select Styles */
.dither-select {
width: 100%;
padding: 8px 12px;
border: 1px solid #e0e0e0;
border-radius: 4px;
background-color: white;
font-size: 14px;
color: var(--text-color);
cursor: pointer;
}
/* Button Styles */
.action-panel {
display: flex;
gap: var(--spacing-unit);
}
.btn {
flex: 1;
padding: 12px 24px;
border: none;
border-radius: 4px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
}
.btn-primary {
background-color: var(--primary-color);
color: white;
}
.btn-primary:hover {
background-color: var(--primary-dark);
}
.btn-secondary {
background-color: #f5f5f5;
color: var(--secondary-color);
}
.btn-secondary:hover {
background-color: #e0e0e0;
}
/* Main Content Area */
.main-content {
flex: 1;
min-height: 600px;
background: var(--panel-background);
border-radius: var(--border-radius);
box-shadow: var(--shadow);
overflow: hidden;
}
.canvas-container {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
}
canvas {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
/* Responsive Design */
@media (max-width: 1024px) {
.container {
flex-direction: column;
}
.sidebar {
width: 100%;
}
.main-content {
min-height: 400px;
}
}
document.addEventListener('DOMContentLoaded', function() {
// DOM elements
const fileUpload = document.getElementById('fileUpload');
const gridSize = document.getElementById('gridSize');
const brightness = document.getElementById('brightness');
const contrast = document.getElementById('contrast');
const gamma = document.getElementById('gamma');
const smoothing = document.getElementById('smoothing');
const ditherType = document.getElementById('ditherType');
const resetButton = document.getElementById('resetButton');
const saveButton = document.getElementById('saveButton');
const gridSizeVal = document.getElementById('gridSizeVal');
const brightnessVal = document.getElementById('brightnessVal');
const contrastVal = document.getElementById('contrastVal');
const gammaVal = document.getElementById('gammaVal');
const smoothingVal = document.getElementById('smoothingVal');
const halftoneCanvas = document.getElementById('halftoneCanvas');
// Global variables for preview
let imageElement = null;
let videoElement = null;
let isVideo = false;
let animationFrameId;
// Default parameter values
const defaults = {
gridSize: 20,
brightness: 20,
contrast: 0,
gamma: 1.0,
smoothing: 0,
ditherType: "None"
};
// Debounce helper to limit update frequency.
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
function updateAndProcess() {
gridSizeVal.textContent = gridSize.value;
brightnessVal.textContent = brightness.value;
contrastVal.textContent = contrast.value;
gammaVal.textContent = gamma.value;
smoothingVal.textContent = smoothing.value;
if (imageElement || videoElement) {
processFrame();
}
}
const debouncedUpdate = debounce(updateAndProcess, 150);
// Attach listeners to controls.
gridSize.addEventListener('input', debouncedUpdate);
brightness.addEventListener('input', debouncedUpdate);
contrast.addEventListener('input', debouncedUpdate);
gamma.addEventListener('input', debouncedUpdate);
smoothing.addEventListener('input', debouncedUpdate);
ditherType.addEventListener('change', debouncedUpdate);
fileUpload.addEventListener('change', handleFileUpload);
function handleFileUpload(e) {
const file = e.target.files[0];
if (!file) return;
const fileURL = URL.createObjectURL(file);
if (file.type.startsWith('video/')) {
isVideo = true;
if (videoElement) {
videoElement.src = fileURL;
} else {
videoElement = document.createElement('video');
videoElement.crossOrigin = "anonymous";
videoElement.src = fileURL;
videoElement.autoplay = true;
videoElement.loop = true;
videoElement.muted = true;
videoElement.playsInline = true;
videoElement.setAttribute("webkit-playsinline", "true");
videoElement.addEventListener('loadeddata', () => {
setupCanvasDimensions(videoElement.videoWidth, videoElement.videoHeight);
videoElement.play();
processVideoFrame();
});
videoElement.addEventListener('error', (e) => {
console.error("Error loading video:", e);
});
}
} else if (file.type.startsWith('image/')) {
isVideo = false;
if (videoElement) {
cancelAnimationFrame(animationFrameId);
videoElement.pause();
}
imageElement = new Image();
imageElement.src = fileURL;
imageElement.addEventListener('load', () => {
setupCanvasDimensions(imageElement.width, imageElement.height);
processFrame();
});
}
}
function setupCanvasDimensions(width, height) {
const maxWidth = window.innerWidth * 0.8;
const maxHeight = window.innerHeight * 0.8;
let newWidth = width, newHeight = height;
if (width > maxWidth || height > maxHeight) {
const ratio = Math.min(maxWidth / width, maxHeight / height);
newWidth = width * ratio;
newHeight = height * ratio;
}
halftoneCanvas.width = newWidth;
halftoneCanvas.height = newHeight;
}
function processFrame() {
if (!imageElement && !videoElement) return;
generateHalftone(halftoneCanvas, 1);
}
function processVideoFrame() {
if (!isVideo) return;
processFrame();
animationFrameId = requestAnimationFrame(processVideoFrame);
}
// Generate halftone: compute grayscale per grid cell by iterating over full‑resolution data.
function generateHalftone(targetCanvas, scaleFactor) {
const previewWidth = halftoneCanvas.width;
const previewHeight = halftoneCanvas.height;
const targetWidth = previewWidth * scaleFactor;
const targetHeight = previewHeight * scaleFactor;
targetCanvas.width = targetWidth;
targetCanvas.height = targetHeight;
// Draw the full‑resolution image/video onto a temporary canvas.
const tempCanvas = document.createElement('canvas');
tempCanvas.width = targetWidth;
tempCanvas.height = targetHeight;
const tempCtx = tempCanvas.getContext('2d');
if (isVideo) {
tempCtx.drawImage(videoElement, 0, 0, targetWidth, targetHeight);
} else {
tempCtx.drawImage(imageElement, 0, 0, targetWidth, targetHeight);
}
const imgData = tempCtx.getImageData(0, 0, targetWidth, targetHeight);
const data = imgData.data;
const brightnessAdj = parseInt(brightness.value, 10);
const contrastAdj = parseInt(contrast.value, 10);
const gammaValNum = parseFloat(gamma.value);
const contrastFactor = (259 * (contrastAdj + 255)) / (255 * (259 - contrastAdj));
// Compute grayscale value per pixel.
const grayData = new Float32Array(targetWidth * targetHeight);
for (let i = 0; i < data.length; i += 4) {
const r = data[i], g = data[i+1], b = data[i+2];
let gray = 0.299 * r + 0.587 * g + 0.114 * b;
gray = contrastFactor * (gray - 128) + 128 + brightnessAdj;
gray = Math.max(0, Math.min(255, gray));
gray = 255 * Math.pow(gray / 255, 1 / gammaValNum);
grayData[i / 4] = gray;
}
// Divide the image into grid cells.
const grid = parseInt(gridSize.value, 10) * scaleFactor;
const numCols = Math.ceil(targetWidth / grid);
const numRows = Math.ceil(targetHeight / grid);
let cellValues = new Float32Array(numRows * numCols);
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
let sum = 0, count = 0;
const startY = row * grid;
const startX = col * grid;
const endY = Math.min(startY + grid, targetHeight);
const endX = Math.min(startX + grid, targetWidth);
for (let y = startY; y < endY; y++) {
for (let x = startX; x < endX; x++) {
sum += grayData[y * targetWidth + x];
count++;
}
}
cellValues[row * numCols + col] = sum / count;
}
}
// Apply smoothing if enabled.
const smoothingStrength = parseFloat(smoothing.value);
if (smoothingStrength > 0) {
cellValues = applyBoxBlur(cellValues, numRows, numCols, smoothingStrength);
}
// Apply dithering if selected.
const selectedDither = ditherType.value;
if (selectedDither === "FloydSteinberg") {
applyFloydSteinbergDithering(cellValues, numRows, numCols);
} else if (selectedDither === "Ordered") {
applyOrderedDithering(cellValues, numRows, numCols);
} else if (selectedDither === "Noise") {
applyNoiseDithering(cellValues, numRows, numCols);
}
// Draw the halftone dots.
const ctx = targetCanvas.getContext('2d');
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, targetWidth, targetHeight);
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
const brightnessValue = cellValues[row * numCols + col];
const norm = brightnessValue / 255;
const maxRadius = grid / 2;
const radius = maxRadius * (1 - norm);
if (radius > 0.5) {
ctx.beginPath();
const centerX = col * grid + grid / 2;
const centerY = row * grid + grid / 2;
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
ctx.fillStyle = 'black';
ctx.fill();
}
}
}
}
// 3× Box Blur for smoothing grid cell values.
function applyBoxBlur(cellValues, numRows, numCols, strength) {
let result = new Float32Array(cellValues);
const passes = Math.floor(strength);
for (let p = 0; p < passes; p++) {
let temp = new Float32Array(result.length);
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
let sum = 0, count = 0;
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
const r = row + dy, c = col + dx;
if (r >= 0 && r < numRows && c >= 0 && c < numCols) {
sum += result[r * numCols + c];
count++;
}
}
}
temp[row * numCols + col] = sum / count;
}
}
result = temp;
}
const frac = strength - Math.floor(strength);
if (frac > 0) {
for (let i = 0; i < result.length; i++) {
result[i] = cellValues[i] * (1 - frac) + result[i] * frac;
}
}
return result;
}
function applyFloydSteinbergDithering(cellValues, numRows, numCols) {
const threshold = 128;
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
const index = row * numCols + col;
const oldVal = cellValues[index];
const newVal = oldVal < threshold ? 0 : 255;
const error = oldVal - newVal;
cellValues[index] = newVal;
if (col + 1 < numCols) {
cellValues[row * numCols + (col + 1)] += error * (7 / 16);
}
if (row + 1 < numRows) {
if (col - 1 >= 0) {
cellValues[(row + 1) * numCols + (col - 1)] += error * (3 / 16);
}
cellValues[(row + 1) * numCols + col] += error * (5 / 16);
if (col + 1 < numCols) {
cellValues[(row + 1) * numCols + (col + 1)] += error * (1 / 16);
}
}
}
}
}
function applyOrderedDithering(cellValues, numRows, numCols) {
const bayerMatrix = [[0,2],[3,1]];
const matrixSize = 2;
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
const index = row * numCols + col;
const threshold = ((bayerMatrix[row % matrixSize][col % matrixSize] + 0.5) *
(255 / (matrixSize * matrixSize)));
cellValues[index] = cellValues[index] < threshold ? 0 : 255;
}
}
}
function applyNoiseDithering(cellValues, numRows, numCols) {
const threshold = 128;
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
const index = row * numCols + col;
const noise = (Math.random() - 0.5) * 50;
const adjustedVal = cellValues[index] + noise;
cellValues[index] = adjustedVal < threshold ? 0 : 255;
}
}
}
resetButton.addEventListener('click', () => {
gridSize.value = defaults.gridSize;
brightness.value = defaults.brightness;
contrast.value = defaults.contrast;
gamma.value = defaults.gamma;
smoothing.value = defaults.smoothing;
ditherType.value = defaults.ditherType;
updateAndProcess();
});
saveButton.addEventListener('click', () => {
if (!imageElement && !videoElement) return;
const exportCanvas = document.createElement('canvas');
generateHalftone(exportCanvas, 2);
const dataURL = exportCanvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = dataURL;
link.download = 'halftone.png';
link.click();
});
setupCanvasDimensions(800, 600);
const ctx = halftoneCanvas.getContext('2d');
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, halftoneCanvas.width, halftoneCanvas.height);
// Automatically load the default video.
(function loadDefaultVideo() {
const videoURL = "https://i.imgur.com/5PrJCc2.mp4";
isVideo = true;
videoElement = document.createElement('video');
videoElement.crossOrigin = "anonymous";
videoElement.playsInline = true;
videoElement.setAttribute("webkit-playsinline", "true");
videoElement.src = videoURL;
videoElement.autoplay = true;
videoElement.loop = true;
videoElement.muted = true;
videoElement.addEventListener('loadeddata', () => {
setupCanvasDimensions(videoElement.videoWidth, videoElement.videoHeight);
videoElement.play();
processVideoFrame();
});
videoElement.addEventListener('error', (e) => {
console.error("Error loading default video:", e);
});
})();
});
Also see: Tab Triggers