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 id="stage">
<canvas id="canvas"></canvas>
<a id="imageLink" href="" download>
<img id="image"/>
</a>
<div id="frameCounter"></div>
</div>
body
background: #333332
#stage
position: absolute
width: 95vh
height: 95vh
margin: auto
top: 0
bottom: 0
left: 0
right: 0
background: #222222
filter: drop-shadow(0 0 20px rgba(0,0,0,0.5))
.particle
display: none
position: absolute
top: 0
left: 0
.particleDisplay
position: absolute
width: 100px
height: 100px
transform: translate3d(-50px, -50px, 0)
background: rgba(0,0,0,0.2)
.activator
display: none
position: absolute
top: 0
left: 0
.activatorDisplay
position: absolute
width: 10px
height: 10px
transform: translate(-5px, -5px)
background: rgba(255,0,0,1)
#canvas
position: absolute
top: 0
left: 0
height: 95vh
width: 95vh
#image
display: none
position: absolute
top: 0
left: 0
#frameCounter
color: white
background: black
font-family: "Courier New"
font-size: 15px
position: absolute
padding: 3px
z-index: 10000
import $ from "https://cdn.skypack.dev/jquery@3.6.0";
let TAU = Math.PI * 2;
let HALF_TURN = Math.PI;
let QUARTER_TURN = TAU / 4;
var stageWidth = 1080;
var stageHeight = 1080;
let numRows = 8;
let numCols = 3;
var settings = {
numParticles: 2800,
numActivators: 12
,//numRows * numCols,
cellSizeX: stageWidth / 8,
cellSizeY: stageHeight / 8,
numFrames: 480 * 2,
record: false
};
let frameCount = 0;
let particles = Array.apply(null, { length: settings.numParticles });
let activators = Array.apply(null, { length: settings.numActivators });
const $stage = $("#stage");
const $canvas = $("#canvas");
const $image = $("#image");
var cellParticles = [];
var numCellsX = Math.ceil(stageWidth / settings.cellSizeX);
var numCellsY = Math.ceil(stageHeight / settings.cellSizeY);
var rAF;
let borderX = settings.cellSizeX * 2;
let borderY = settings.cellSizeY * 2;
let fullTripX = stageWidth + borderX * 2;
let fullTripY = stageHeight + borderY * 2;
const zip = new JSZip();
let colormapOffsetX = 0;
//----------------------------------------------------------------
// $(window).click(() => {
// if(settings.record == false){
// settings.record = true;
// frameCount = 0;
// }
// })
//----------------------------------------------------------------
class Activator {
constructor(index) {
this.age = 0;
this.adjacentParticles = [];
this.index = index;
}
}
class Particle {
constructor(index) {
this.x = 0;
this.y = 0;
this.power = 0;
this.$el = null;
this.index = index;
}
}
//----------------------------------------------------------------
loadColorMap(setup);
//----------------------------------------------------------------
function setup() {
particles = particles.map((p, i) => {
p = new Particle(i);
p.x = fullTripX * Math.random() - settings.cellSizeX;
p.y = fullTripY * Math.random() - settings.cellSizeY;
p.cell = getCellLocation(p.x, p.y);
p.$el = $(`
<div class='particle'>
<div class='particleDisplay'></div>
</div>
`);
p.$el.css("transform", `translate3d(${p.x}px, ${p.y}px, 0px)`);
// $stage.append(p.$el);
return p;
});
activators = activators.map((a, i) => {
a = new Activator(i);
a.col = i % numCols;
a.row = Math.floor(i/numCols);
// a.x = (stageWidth + borderX * 2) * ((-1 + a.col) / (numCols));
// a.y = (stageHeight + borderX*2 ) * ((-1 + a.row) / numRows);
a.homeX = a.x = stageWidth / 2;
a.homeY = a.y = stageWidth / 2;
a.cell = getCellLocation(a.x, a.y);
a.angle = -i * TAU / (settings.numActivators);
// if (i == settings.numActivators / 2){
// a.angle = -(settings.numActivators) * TAU / (settings.numActivators + 2);
// }
// a.$el = $(`
// <div class='activator'>
// <div class='activatorDisplay'></div>
// </div>
// `);
// a.$el.css("transform", `translate3d(${a.x}px, ${a.y}px, 0px)`);
// $stage.append(a.$el);
// console.log(`activator ${i}`,a.row, a.col, " | x,y:", a.x, a.y)
return a;
});
$canvas[0].width = stageWidth;
$canvas[0].height = stageHeight;
//$stage.css({
// "width": stageWidth + "px",
// "height": stageHeight + "px",
//})
// initial Fill
var ctx = $canvas[0].getContext("2d");
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = `rgba(${0x22},${0x22},${0x22},1)`;
ctx.fillRect(0, 0, stageWidth, stageHeight);
loop();
updateActivators();
}
function loop() {
// console.log("----------- loop() ------------")
updateActivators();
updateParticles();
draw();
rAF = requestAnimationFrame(loop);
frameCount++;
}
//----------------------------------------------------------------
function updateActivators() {
//chill for now
activators.forEach((a, i) => {
let dir = 1//(i * 1.25) % 2 ? -1 : 1;
a.angle += dir * TAU / settings.numFrames;
let wobble = 350;
let radius = 200;
let speed = fullTripX / settings.numFrames
let angle = 0;
// a.homeX += speed;
// a.homeY -= speed;
if (a.homeX > stageWidth + borderX ){
a.homeX -= fullTripX;
}
if (a.homeX < -borderX){
a.homeX += fullTripX;
}
if (a.homeY > stageHeight + borderY){
a.homeY -= fullTripY;
}
if (a.homeY < -borderY){
a.homeY += fullTripY;
}
a.x = a.homeX + Math.cos(a.angle) * wobble;
a.y = a.homeY + Math.sin(a.angle) * wobble;
a.cell = getCellLocation(a.x, a.y);
});
}
function updateParticles() {
// colormapOffsetX = (colormapOffsetX + 1) % 100;
cellParticles = [];
let angle = Math.PI / 2;
let speed = fullTripX / settings.numFrames
particles.forEach((p, i) => {
p.power = 0;
let modifiedAngle = 0;
p.x += speed * Math.cos(angle + modifiedAngle);
p.y += speed * Math.sin(angle + modifiedAngle);
if (p.x > stageWidth + borderX){
p.x -= fullTripX;
}
if (p.x < -borderX){
p.x += fullTripX;
}
if (p.y > stageHeight + borderY){
p.y -= fullTripY;
}
if (p.y < -borderY){
p.y += fullTripY;
}
p.color = getPixel(colorMapData, (p.x + colormapOffsetX) / stageWidth, p.y / stageHeight);
p.cell = getCellLocation(p.x, p.y);
addToCell(p.cell.x, p.cell.y, p);
});
// console.log("updateParticles:: activators")
activators.forEach((a, i) => {
a.adjacentParticles = getParticlesInAdjacentCells(a.cell.x, a.cell.y);
// get distance to each particle
a.distances = a.adjacentParticles.map((p, j) => {
return dist(a.x, a.y, p.x, p.y);
});
a.adjacentParticles.forEach((p, i) => {
// activator strengh is proportional to distance to particle (and velocity?)
// actuator vectors on a single particle are additive (could change the blend equation later)
// particle can trigger an event or be simple power comparison with easing
let maxDistance = settings.cellSizeX * 1.7;
let newPower = Math.max(0, 1 - a.distances[i] / maxDistance)
p.power += newPower;
});
// console.log(`activator ${i}`,a.row, a.col, " | x,y:", a.x, a.y)
});
}
function getParticlesInAdjacentCells(x, y) {
let adjacentParticles = [];
for (let i = x - 2; i <= x + 2; i++) {
if (i >= 0 && i < numCellsX) {
for (let j = y - 2; j <= y + 2; j++) {
if (j >= 0 && j < numCellsY) {
adjacentParticles = adjacentParticles.concat(getCell(i,j));
}
}
}
}
return adjacentParticles;
}
function updateParticlePower() {}
function getCell(x, y) {
if (!cellParticles[x]) cellParticles[x] = [];
if (!cellParticles[x][y]) cellParticles[x][y] = [];
return cellParticles[x][y];
}
function addToCell(x, y, particle) {
if (!cellParticles[x]) cellParticles[x] = [];
if (!cellParticles[x][y]) cellParticles[x][y] = [];
cellParticles[x][y].push(particle);
return cellParticles[x][y];
}
function getCellLocation(x, y) {
// console.log("getCellLocation");
return {
x: Math.floor(numCellsX * (x / stageWidth)),
y: Math.floor(numCellsY * (y / stageHeight))
};
}
//----------------------------------------------------------------
function draw() {
let HALF_PI = Math.PI / 2;
// draw to stage
var ctx = $canvas[0].getContext("2d");
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = `rgba(${0x22},${0x22},${0x22},0.5)`;
ctx.fillRect(0, 0, $canvas[0].width, $canvas[0].height);
// ctx.clearRect(0, 0, $canvas[0].width, $canvas[0].height);
ctx.globalCompositeOperation = "screen";
// ctx.globalCompositeOperation = "multiply";
// ctx.fillStyle = "rgba(0,0,0,0.1)";
particles.forEach((p, i) => {
// p.$el.css({
// transform:
// `translate3d(${p.x}px, ${p.y}px, 0px) scale(${Math.min(1, p.power)})`
// });
let a = p.power * p.power * p.power *0.25;
// ctx.fillStyle = `rgba(${r},${g},${b},${a})`;
ctx.fillStyle = `rgba(${p.color >> 16},${(p.color >> 8) & 0xff},${p.color & 0xff},${a})`;
// console.log(`rgba(${p.color >> 16},${(p.color >> 8) & 0xff},${p.color & 0xff},${a})`)
let rad = 75
let w = p.power * rad
let h = p.power * rad
let SIXTY_RAD = (2 * Math.PI) / 6;
ctx.beginPath();
// ctx.moveTo(
// p.x + p.power * rad * Math.cos(HALF_PI),
// p.y + p.power * rad * Math.sin(HALF_PI)
// );
// ctx.lineTo(
// p.x + p.power * rad * Math.cos(2 * SIXTY_RAD + HALF_PI),
// p.y + p.power * rad * Math.sin(2 * SIXTY_RAD + HALF_PI)
// );
// ctx.lineTo(
// p.x + p.power * rad * Math.cos(4 * SIXTY_RAD + HALF_PI),
// p.y + p.power * rad * Math.sin(4 * SIXTY_RAD + HALF_PI)
// );
// ctx.fillRect(p.x-w/2, p.y-h/2,w, h);
// ctx.arc(p.x, p.y, p.power * rad, 0, TAU);
// ctx.fill();
let center = {x: stageWidth * 0.5, y: stageHeight * 0.5};
// let angleToCenter = Math.atan2(p.y - center.y, p.x - center.x);
let angleToCenter = -Math.atan2(center.y - p.y, center.x - p.x);
drawRotatedSquare(ctx, p.x, p.y, w, angleToCenter)
});
activators.forEach((a, i) => {
// ctx.fillStyle = "#F0F"
// ctx.fillRect(a.x, a.y, 10, 10);
// ctx.fill();
// a.adjacentParticles.forEach((p, i) => {
// ctx.beginPath();
// ctx.moveTo(p.x, p.y);
// ctx.lineTo(a.x, a.y);
// let maxDistance = settings.cellSizeX * 1;
// let newPower = Math.max(0, 1 - a.distances[i] / maxDistance)
// ctx.strokeStyle = `rgba(0,0,0,${newPower})`;
// ctx.stroke();
// });
});
if (settings.record){
if (frameCount < settings.numFrames){
$("#frameCounter").text( pad(frameCount, 3));
zip.file(
`frame_${pad(frameCount, 3)}.png`,
dataURItoBlob($canvas[0].toDataURL( 'image/png' )),
{base64: true}
);
} else if (frameCount == settings.numFrames){
stopRecording();
cancelAnimationFrame(rAF)
}
}
}
function stopRecording() {
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "frames.zip");
});
}
//----------------------------------------------------------------
function pad(num, len){
while(num.toString().length < len ){
num = "0" + num.toString()
}
return num;
}
function dist(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
function dataURItoBlob( dataURI ) {
// Convert Base64 to raw binary data held in a string.
var byteString = atob(dataURI.split(',')[1]);
// Separate the MIME component.
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// Write the bytes of the string to an ArrayBuffer.
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// Write the ArrayBuffer to a BLOB and you're done.
var bb = new Blob([ab]);
return bb;
}
// ----------------------
function drawRotatedSquare(ctx, x, y, size, angle){
let halfSize = size * 0.5;
let x0 = -halfSize;
let x1 = halfSize;
let y0 = -halfSize;
let y1 = halfSize;
let points = [];
points.push([x0, y0]);
points.push([x1, y0]);
points.push([x1, y1]);
points.push([x0, y1]);
points = points.map(p => getRotatedPoint(p[0], p[1], angle));
points = points.map(p => [x + p[0], y + p[1]]);
ctx.beginPath();
ctx.moveTo(points[0][0],points[0][1]);
ctx.lineTo(points[1][0],points[1][1]);
ctx.lineTo(points[2][0],points[2][1]);
ctx.lineTo(points[3][0],points[3][1]);
ctx.lineTo(points[0][0],points[0][1]);
ctx.closePath();
ctx.fill();
}
function getRotatedPoint(x,y, angle){
let cos = Math.cos(angle),
sin = Math.sin(angle),
nx = (cos * x) + (sin * y),
ny = (cos * y) - (sin * x);
return [nx, ny];
}
// ----------------------
var colorMap;
var colorMapCanvas;
var colorMapCtx;
var colorMapData;
function loadColorMap(callback) {
var imgSrc =
"https://assets.codepen.io/98232/Imagemap+2048_1.png";
//"https://assets.codepen.io/98232/comp54.jpg";
colorMap = new Image();
colorMap.crossOrigin = "anonymous";
colorMap.src = imgSrc;
colorMap.onload = function() {
postColorMapLoad();
callback();
};
}
function postColorMapLoad() {
// create the sampler
var colorMapCanvas = document.createElement("canvas");
// $("body").append($(colorMapCanvas));
colorMapCanvas.height = colorMapCanvas.width = 2048;
colorMapCtx = colorMapCanvas.getContext("2d");
colorMapCtx.drawImage(colorMap, 0, 0, 2048, 2048);
colorMapData = colorMapCtx.getImageData(0, 0, 2048, 2048);
}
function getPixel(colorMapData, propX, propY) {
var data = colorMapData.data;
var col = (propX * colorMapData.width) << 2;
var row = (propY * colorMapData.height) >> 0;
var rowWidth = colorMapData.width << 2;
return (data[col + (row * rowWidth) + 0] << 16) | (data[col + (row * rowWidth) + 1] << 8) | data[col + (row * rowWidth) + 2];
}
Also see: Tab Triggers