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.
<canvas></canvas>
body {
margin: 0;
}
// Initial Setup
const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;
// Variables
const mouse = {
x: innerWidth / 2,
y: innerHeight / 2
}
const colors = ['#2185C5', '#7ECEFD', '#FFF6E5', '#FF7F66'];
// Event Listeners
addEventListener('mousemove', event => {
mouse.x = event.clientX;
mouse.y = event.clientY;
});
addEventListener('resize', () => {
canvas.width = innerWidth;
canvas.height = innerHeight;
init();
});
// Utility Functions
function randomIntFromRange(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function randomColor(colors) {
return colors[Math.floor(Math.random() * colors.length)];
}
function distance(x1, y1, x2, y2) {
const xDist = x2 - x1;
const yDist = y2 - y1;
return Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
}
/**
* Rotates coordinate system for velocities
*
* Takes velocities and alters them as if the coordinate system they're on was rotated
*
* @param Object | velocity | The velocity of an individual particle
* @param Float | angle | The angle of collision between two objects in radians
* @return Object | The altered x and y velocities after the coordinate system has been rotated
*/
function rotate(velocity, angle) {
const rotatedVelocities = {
x: velocity.x * Math.cos(angle) - velocity.y * Math.sin(angle),
y: velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle)
};
return rotatedVelocities;
}
/**
* Swaps out two colliding particles' x and y velocities after running through
* an elastic collision reaction equation
*
* @param Object | particle | A particle object with x and y coordinates, plus velocity
* @param Object | otherParticle | A particle object with x and y coordinates, plus velocity
* @return Null | Does not return a value
*/
function resolveCollision(particle, otherParticle) {
const xVelocityDiff = particle.velocity.x - otherParticle.velocity.x;
const yVelocityDiff = particle.velocity.y - otherParticle.velocity.y;
const xDist = otherParticle.x - particle.x;
const yDist = otherParticle.y - particle.y;
// Prevent accidental overlap of particles
if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {
// Grab angle between the two colliding particles
const angle = -Math.atan2(otherParticle.y - particle.y, otherParticle.x - particle.x);
// Store mass in var for better readability in collision equation
const m1 = particle.mass;
const m2 = otherParticle.mass;
// Velocity before equation
const u1 = rotate(particle.velocity, angle);
const u2 = rotate(otherParticle.velocity, angle);
// Velocity after 1d collision equation
const v1 = { x: u1.x * (m1 - m2) / (m1 + m2) + u2.x * 2 * m2 / (m1 + m2), y: u1.y };
const v2 = { x: u2.x * (m1 - m2) / (m1 + m2) + u1.x * 2 * m2 / (m1 + m2), y: u2.y };
// Final velocity after rotating axis back to original location
const vFinal1 = rotate(v1, -angle);
const vFinal2 = rotate(v2, -angle);
// Swap particle velocities for realistic bounce effect
particle.velocity.x = vFinal1.x;
particle.velocity.y = vFinal1.y;
otherParticle.velocity.x = vFinal2.x;
otherParticle.velocity.y = vFinal2.y;
}
}
// Objects
function Particle(x, y, radius, color) {
this.x = x;
this.y = y;
this.velocity = {
x: (Math.random() - 0.5) * 5,
y: (Math.random() - 0.5) * 5
}
this.radius = radius;
this.color = randomColor(colors);
this.mass = 1;
this.opacity = 0;
this.update = particles => {
this.draw();
//Detect collisions against all other circles
for(let i=0; i<particles.length; i++) {
//do not check this against itself in the array
if(this === particles[i]) continue;
//Everytime we draw we are checking if distance between circle is < 0
if(distance(this.x, this.y, particles[i].x, particles[i].y) - this.radius * 2 < 0) {
resolveCollision(this, particles[i]);
}
}
if(this.x - this.radius <= 0|| this.x + this.radius >= innerWidth) {
this.velocity.x = -this.velocity.x;
}
if(this.y - this.radius <= 0 || this.y + this.radius >= innerHeight) {
this.velocity.y = -this.velocity.y;
}
//mouse collision detection
if(distance(mouse.x, mouse.y, this.x, this.y) < 120 && this.opacity < 0.5) {
this.opacity += 0.10;
} else if (this.opacity > 0) {
this.opacity -= 0.10;
this.opacity = Math.max(0, this.opacity);
}
this.x += this.velocity.x;
this.y += this.velocity.y;
}
this.draw = () => {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.save();
c.globalAlpha = this.opacity;
c.fillStyle = this.color;
c.fill();
c.restore();
c.strokeStyle = this.color;
c.stroke();
c.closePath();
}
}
// Implementation
let particles = [];
function init() {
for (let i = 0; i < 100; i++) {
const radius = 15;
let x = randomIntFromRange(radius, innerWidth - radius);
let y = randomIntFromRange(radius, innerHeight - radius);
const color = 'blue';
//Only run this for all particls after i=0
if(i !== 0) {
//Loop through all other particls that exist
//compare locations
for(let j=0; j < particles.length; j++) {
//Pass in current particle and all other partices to conditional
//subtract radius * 2 for both circles radius
if(distance(x, y, particles[j].x, particles[j].y) - radius * 2 < 0) {
//regenerate x and y
x = randomIntFromRange(radius, innerWidth - radius);
y = randomIntFromRange(radius, innerHeight - radius);
//reset loop to check against all the other particles now we have new co-ordinates
//Will re-loop every time and compare.
j = -1;
}
}
}
particles.push(new Particle(x, y, radius, color));
}
}
// Animation Loop
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => {
particle.update(particles);
});
}
init();
animate();
Also see: Tab Triggers