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.
#app
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
display: grid;
place-items: center;
background: hsl(0, 0%, 20%);
}
#app {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
flex-gap: 1rem;
gap: 1rem;
}
canvas {
height: 200px;
width 300px;
background: hsl(0, 0%, 20%);
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
}
.controls {
position: relative;
}
.record,
.stop {
border-radius: 50%;
border: 4px solid white;
display: flex;
align-items: center;
justify-content: center;
font-size: 0;
height: 48px;
width: 48px;
background: none;
position: relative;
overflow: hidden;
transform: translate(calc(var(--x, 0) * 1%), calc(var(--y, 0) * 1%)) scale(var(--scale, 1));
transition: transform 0.1s;
}
.record {
color: hsl(10, 80%, 50%);
}
.record svg {
transform: scale(calc(5 - (var(--active, 0) * 4)));
transform-origin: 20% 50%;
transition: transform 0.1s;
}
.record,
.stop {
&:hover {
--scale: 1.1;
}
&:active {
--scale: 0.9;
}
}
.stop {
position: absolute;
left: 125%;
border: none;
background: none;
top: 50%;
--y: -50;
color: hsl(0, 0%, 100%);
}
.stop svg
.record svg {
height: 65%;
fill: currentColor;
}
.reveal {
cursor: pointer;
position: fixed;
top: 1rem;
right: 1rem;
height: 48px;
width: 48px;
display: grid;
place-items: center;
padding: 0;
background: none;
border: none;
}
.reveal svg {
width: 100%;
fill: hsl(0, 0%, 6%);
}
.reveal[aria-pressed="true"] svg:nth-of-type(1),
.reveal svg:nth-of-type(2) {
display: none;
}
.reveal[aria-pressed="true"] svg:nth-of-type(2) {
display: block;
}
.recordings {
font-family: sans-serif;
color: hsl(0, 0%, 100%);
width: 300px;
padding: 1.25rem;
}
.recordings summary {
font-weight: bold;
}
.recordings__empty-message {
padding: 1rem;
text-align: center;
}
.recordings__list {
padding: 0.5rem 0;
margin: 0;
}
.recordings__list > * + * {
margin-top: 0.5rem;
}
.recordings__recording {
display: flex;
flex-direction: row;
flex-gap: 0.125rem;
gap: 0.125rem;
align-items: center;
}
.recordings__recording span {
flex: 1 1 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.recordings__recording:nth-of-type(even) {
background: hsl(0, 0%, 25%);
}
.recordings__control {
background: var(--bg);
color: hsl(0, 0%, 100%);
display: grid;
place-items: center;
height: 44px;
width: 44px;
flex: 0 0 44px;
border-radius: 6px;
cursor: pointer;
}
.recordings__control svg {
fill: currentColor;
width: 75%;
}
.recordings__play {
--bg: hsl(120, 50%, 50%);
}
.recordings__delete {
--bg: hsl(10, 50%, 50%);
}
.recordings__download {
--bg: hsl(210, 50%, 50%);
}
import React from 'https://cdn.skypack.dev/react'
import { render } from 'https://cdn.skypack.dev/react-dom'
import { Canvas, useFrame } from 'https://cdn.skypack.dev/@react-three/fiber'
import * as THREE from 'https://cdn.skypack.dev/three@v0.137'
import gsap from 'https://cdn.skypack.dev/gsap'
const ROOT_NODE = document.querySelector('#app')
const CONFIG = {
fft: 64,
show: true,
duration: 0.1,
fps: 24,
barWidth: 4,
barMinHeight: 0.04,
barMaxHeight: 0.8,
barGap: 2,
}
// Set the global FPS for the canvas...
gsap.ticker.fps(CONFIG.fps)
const usePersistentState = (key, initialValue) => {
const [state, setState] = React.useState(
window.localStorage.getItem(key)
? JSON.parse(window.localStorage.getItem(key))
: initialValue
)
React.useEffect(() => {
// Stringify so we can read it back
window.localStorage.setItem(key, JSON.stringify(state))
}, [key, state])
return [state, setState]
}
const Box = props => {
return (
<mesh {...props} ref={props.innerRef}>
<boxGeometry args={[1, 1, 1]} />
<meshLambertMaterial map={props.texture.current} shininess={10} />
</mesh>
)
}
const Bars = ({ meshRef, texture }) => {
const bars = React.useRef(
new Array(CONFIG.fft / 2).fill().map(b => React.useRef())
)
React.useEffect(() => {
bars.current.forEach(bar => {
gsap.set(bar.current.scale, {
y: 0.5,
})
})
// Set the bind
meshRef.current = bars.current
}, [])
return (
<group rotation={[0, 0, 0]} position={[-10, 0, 5]}>
{bars.current.map((bar, index) => (
<Box
innerRef={bar}
texture={texture}
position={[
gsap.utils.distribute({
base: bars.current.length / -2 - 2,
amount: bars.current.length * 1.25,
})(index, bars.current[index], bars.current),
0,
-0.5,
]}
/>
))}
</group>
)
}
const AudioVisualizationThree = ({
timeline,
recording,
recorder,
start,
drawRef,
scrubRef,
metadata,
src,
}) => {
const canvasRef = React.useRef(null)
const meshRef = React.useRef(null)
const textureRef = React.useRef(null)
const contextRef = React.useRef(null)
const audioContextRef = React.useRef(null)
const barsRef = React.useRef([])
React.useEffect(() => {
const createTexture = () => {
const CANVAS = document.createElement('canvas')
const CTX = CANVAS.getContext('2d')
CANVAS.width = canvasRef.current.width
CANVAS.height = canvasRef.current.height
// const fillStyle = CTX.createLinearGradient(
// CANVAS.width / 2,
// 0,
// CANVAS.width / 2,
// CANVAS.height
// )
// // Color stop is three colors
// fillStyle.addColorStop(0.01, 'hsl(0, 80%, 50%)')
// fillStyle.addColorStop(0.99, 'hsl(0, 80%, 50%)')
// fillStyle.addColorStop(0.35, 'hsl(120, 100%, 50%)')
// fillStyle.addColorStop(0.5, 'hsl(120, 100%, 50%)')
// fillStyle.addColorStop(0.65, 'hsl(120, 100%, 50%)')
// CTX.fillStyle = fillStyle
CTX.fillStyle = 'hsl(180, 100%, 50%)'
CTX.fillRect(0, 0, CANVAS.width, CANVAS.height)
textureRef.current = new THREE.CanvasTexture(CANVAS)
textureRef.current.wrapS = THREE.RepeatWrapping
textureRef.current.wrapT = THREE.RepeatWrapping
textureRef.current.mapping = THREE.EquirectangularRefractionMapping
textureRef.current.needsUpdate = true
}
createTexture()
}, [])
const addBars = bars => {
const BAR_DURATION = CONFIG.duration
barsRef.current.push(bars)
for (let b = 0; b < bars.length; b++) {
timeline.current.to(
meshRef.current[b].current.scale,
{
y: gsap.utils.clamp(0.5, 10, bars[b]),
duration: BAR_DURATION,
},
barsRef.current.length * (1 / CONFIG.fps)
)
}
}
const ANALYSE = stream => {
audioContextRef.current = new AudioContext()
const ANALYSER = audioContextRef.current.createAnalyser()
ANALYSER.fftSize = CONFIG.fft
const SOURCE = audioContextRef.current.createMediaStreamSource(stream)
const DATA_ARR = new Uint8Array(ANALYSER.frequencyBinCount)
SOURCE.connect(ANALYSER)
// Reset the bars and pad them out...
if (barsRef.current.length > 0) {
barsRef.current.length = 0
}
if (metadata.current && metadata.current.length > 0) {
metadata.current.length = 0
}
const REPORT = () => {
if (recorder.current && recorder.current.state === 'recording') {
ANALYSER.getByteTimeDomainData(DATA_ARR)
// ANALYSER.getByteFrequencyData(DATA_ARR)
// const VOLUME = Math.floor((Math.max(...DATA_ARR) / 255) * 100)
// console.info(DATA_ARR)
// Each frame is 8 blocks of tweens getting added to the timeline
// But they need to be normalized
const BARS = [...DATA_ARR].map(value => (1 - (value / 128.0)) * 100)
// const BARS = [...DATA_ARR].map(value => (value / 255.0))
addBars(BARS)
// Blocks of Arrays instead for this one.
metadata.current.push(BARS)
}
// if (recording) {
// DRAW()
// }
}
drawRef.current = REPORT
gsap.ticker.add(drawRef.current)
}
React.useEffect(() => {
if (recording && recorder.current) {
ANALYSE(recorder.current.stream)
}
}, [recording, recorder.current])
React.useEffect(() => {
barsRef.current.length = 0
if (src === null) {
metadata.current.length = 0
} else if (src && metadata.current.length) {
metadata.current.forEach(bars => addBars(bars))
// gsap.ticker.add(drawRef.current)
}
}, [src])
return (
<Canvas ref={canvasRef} camera={{ fov: 75, position: [8, 8, 15] }}>
<pointLight position={[10, 20, 50]} />
<Bars texture={textureRef} meshRef={meshRef} />
</Canvas>
)
}
const RecorderControls = ({ onRecord, onStop, recording, paused }) => {
return (
<div className="controls">
<button
className="record"
id="toggle"
onClick={onRecord}
title={recording ? 'Pause Recording' : 'Start Recording'}
style={{ '--active': recording && !paused ? 1 : 0 }}>
Start Recording
<svg viewBox="0 0 448 512" width="100" title="pause">
<path d="M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z" />
</svg>
</button>
{recording ? (
<button
className="stop"
title="Stop Recording"
id="stop"
onClick={onStop}>
Stop Recording
<svg viewBox="0 0 448 512" width="100" title="stop">
<path d="M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48z" />
</svg>
</button>
) : null}
</div>
)
}
const Recordings = ({ recordings, onDelete, onPlay, onDownload }) => {
return (
<details className="recordings">
<summary>{`Recordings [${recordings.length}]`}</summary>
{!recordings ||
(recordings.length === 0 && (
<div className="recordings__empty-message">No Recordings</div>
))}
{recordings.length > 0 ? (
<ul className="recordings__list">
{recordings.map(recording => (
<li className="recordings__recording" key={recording.id}>
<span>{recording.name}</span>
<button
onClick={onPlay}
className="recordings__play recordings__control"
data-recording={recording.id}
title="Play Recording">
<svg viewBox="0 0 448 512" width="100" title="play">
<path d="M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z" />
</svg>
</button>
<button
onClick={onDownload}
className="recordings__download recordings__control"
data-recording={recording.id}
title="Download Recording">
<svg
viewBox="0 0 640 512"
width="100"
title="cloud-download-alt">
<path d="M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zm-132.9 88.7L299.3 420.7c-6.2 6.2-16.4 6.2-22.6 0L171.3 315.3c-10.1-10.1-2.9-27.3 11.3-27.3H248V176c0-8.8 7.2-16 16-16h48c8.8 0 16 7.2 16 16v112h65.4c14.2 0 21.4 17.2 11.3 27.3z" />
</svg>
</button>
<button
onClick={onDelete}
className="recordings__delete recordings__control"
data-recording={recording.id}
title="Delete Recording">
<svg viewBox="0 0 448 512" width="100" title="trash-alt">
<path d="M32 464a48 48 0 0 0 48 48h288a48 48 0 0 0 48-48V128H32zm272-256a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zM432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16- 16V48a16 16 0 0 0-16-16z" />
</svg>
</button>
</li>
))}
</ul>
) : null}
</details>
)
}
// Things need to be passed into this point.
const RecorderPlayback = ({
timeline,
start,
draw,
src,
scrub,
audioRef: propsRef,
}) => {
const audioRef = React.useRef(null)
React.useEffect(() => {
const onUpdate = e => {
switch (e.type) {
case 'play':
if (draw.current) gsap.ticker.add(draw.current)
timeline.current.totalTime(
audioRef.current.currentTime + start.current
)
timeline.current.play()
break
case 'seeking':
case 'seeked':
timeline.current.totalTime(
audioRef.current.currentTime + start.current
)
break
case 'pause':
timeline.current.pause()
break
case 'ended':
timeline.current.pause()
if (scrub) scrub(start.current)
break
}
}
;['play', 'seeking', 'seeked', 'pause', 'ended'].forEach(event =>
audioRef.current.addEventListener(event, onUpdate)
)
// Sync refs
propsRef.current = audioRef.current
return () => {
;['play', 'seeking', 'seeked', 'pause', 'ended'].forEach(event =>
audioRef.current.removeEventListener(event, onUpdate)
)
}
}, [])
React.useEffect(() => {
if (src && src.startsWith('data')) audioRef.current.play()
}, [src])
return <audio src={src} ref={audioRef} controls />
}
const App = () => {
const timeline = React.useRef(gsap.timeline())
const recorder = React.useRef(null)
const start = React.useRef(0)
const audioRef = React.useRef(null)
const draw = React.useRef(() => {})
const metadata = React.useRef([])
const [{ recordings }, setRecordings] = usePersistentState('3d-recordings', {
recordings: [],
})
const [src, setSrc] = React.useState(null)
const [recording, setRecording] = React.useState(false)
const [paused, setPaused] = React.useState(false)
// UTILITY FUNCTION
const reset = () => {
metadata.current.length = 0
gsap.ticker.remove(draw.current)
draw.current = null
timeline.current.clear()
setSrc(null)
}
const scrub = (time = 0, trackTime = 0, onComplete) => {
gsap.to(timeline.current, {
totalTime: time,
onComplete: () => {
audioRef.current.currentTime = trackTime
gsap.ticker.remove(draw.current)
if (onComplete) onComplete()
},
})
}
const onStop = () => {
recorder.current.stop()
}
const onDelete = e => {
if (confirm('Delete Recording?')) {
const idToDelete = parseInt(
e.currentTarget.getAttribute('data-recording'),
10
)
setRecordings({
recordings: [
...recordings.filter(recording => recording.id !== idToDelete),
],
})
reset()
}
}
const onDownload = async e => {
const idToDownload = parseInt(
e.currentTarget.getAttribute('data-recording'),
10
)
const RECORDING = recordings.filter(
recording => recording.id === idToDownload
)[0]
const BLOB = await (await fetch(RECORDING.audioBlob)).blob()
const DOWNLOAD = document.createElement('a')
DOWNLOAD.download = `Recording – ${RECORDING.name}`
DOWNLOAD.href = URL.createObjectURL(BLOB)
document.body.appendChild(DOWNLOAD)
DOWNLOAD.click()
DOWNLOAD.remove()
}
const onPlay = e => {
const idToPlay = parseInt(
e.currentTarget.getAttribute('data-recording'),
10
)
const RECORDING = recordings.filter(
recording => recording.id === idToPlay
)[0]
if (src === RECORDING.audioBlob) return
reset()
// Trigger this by setting a state variable or something.
metadata.current = [...RECORDING.metadata]
setSrc(RECORDING.audioBlob)
}
const onSave = async audioBlob => {
const reader = new FileReader()
reader.onload = e => {
const audioSafe = e.target.result
const timestamp = new Date()
const name = prompt('Recording name?')
setRecordings({
recordings: [
...recordings,
{
audioBlob: audioSafe,
metadata: [...metadata.current],
name: name || timestamp.toUTCString(),
id: timestamp.getTime(),
},
],
})
alert('Recording Saved')
}
await reader.readAsDataURL(audioBlob)
}
const onRecord = () => {
const toggleRecording = async () => {
// If we aren't recording, we need to start a recording.
if (!recording) {
// Reset the timeline
timeline.current.clear()
// Reset the audio tag
const CHUNKS = []
const MEDIA_STREAM = await window.navigator.mediaDevices.getUserMedia({
audio: true,
})
recorder.current = new MediaRecorder(MEDIA_STREAM)
recorder.current.ondataavailable = async event => {
// gsap.ticker.remove(draw.current)
timeline.current.pause()
CHUNKS.push(event.data)
const AUDIO_BLOB = new Blob(CHUNKS, { type: 'audio/ogg' })
const SRC = window.URL.createObjectURL(AUDIO_BLOB)
// Tear down after recording.
recorder.current.stream.getTracks().forEach(t => t.stop())
recorder.current = null
const save = confirm('Save Recording?')
if (save) {
onSave(AUDIO_BLOB)
}
scrub(start.current, 0, () => {
setSrc(SRC)
setRecording(false)
})
}
recorder.current.start()
timeline.current.play()
// Trigger the changes
setSrc(null)
setRecording(true)
} else {
const RECORDING = recorder.current.state === 'recording'
timeline.current[RECORDING ? 'pause' : 'play']()
recorder.current[RECORDING ? 'pause' : 'resume']()
setPaused(RECORDING)
}
}
toggleRecording()
}
return (
<>
<AudioVisualizationThree
start={start}
recording={recording}
recorder={recorder}
timeline={timeline}
drawRef={draw}
metadata={metadata}
src={src}
/>
<RecorderControls
onRecord={onRecord}
recording={recording}
paused={paused}
onStop={onStop}
/>
<RecorderPlayback
src={src}
timeline={timeline}
start={start}
draw={draw}
audioRef={audioRef}
scrub={scrub}
/>
<Recordings
recordings={recordings}
onDownload={onDownload}
onDelete={onDelete}
onPlay={onPlay}
/>
</>
)
}
render(<App />, ROOT_NODE)
Also see: Tab Triggers