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.
<section id="controls-wrapper">
<label>Mass of Added Planet</label>
<select id="masses-list">
<option value="0.000003003">Earth</option>
<option value="0.0009543">Jupiter</option>
<option value="1">Sun</option>
<option value="0.1">Red Dwarf Star</option>
</select>
<button id="reset-button">Reset</button>
</section>
<canvas id="canvas"></canvas>
body {
margin: 0;
overflow: hidden;
background: linear-gradient(to bottom, #cedce7 0%,#596a72 100%);
font-family: arial;
font-size: 13px;
font-weight: bold;
}
#controls-wrapper {
position: absolute;
z-index: 2;
top: 0;
width: 100%;
padding: 10px;
}
#controls-wrapper > select, button {
background-color: #000;
color: #fff;
border: 1px solid #545454;
}
/*
* Gravitational n-body algorithm
*/
class nBodyProblem {
constructor(params) {
this.g = params.g;
this.dt = params.dt;
this.softeningConstant = params.softeningConstant;
this.masses = params.masses;
}
updatePositionVectors() {
const massesLen = this.masses.length;
for (let i = 0; i < massesLen; i++) {
const massI = this.masses[i];
massI.x += massI.vx * this.dt;
massI.y += massI.vy * this.dt;
massI.z += massI.vz * this.dt;
}
return this;
}
updateVelocityVectors() {
const massesLen = this.masses.length;
for (let i = 0; i < massesLen; i++) {
const massI = this.masses[i];
massI.vx += massI.ax * this.dt;
massI.vy += massI.ay * this.dt;
massI.vz += massI.az * this.dt;
}
}
updateAccelerationVectors() {
const massesLen = this.masses.length;
for (let i = 0; i < massesLen; i++) {
let ax = 0;
let ay = 0;
let az = 0;
const massI = this.masses[i];
for (let j = 0; j < massesLen; j++) {
if (i !== j) {
const massJ = this.masses[j];
const dx = massJ.x - massI.x;
const dy = massJ.y - massI.y;
const dz = massJ.z - massI.z;
const distSq = dx * dx + dy * dy + dz * dz;
const f =
(this.g * massJ.m) /
(distSq * Math.sqrt(distSq + this.softeningConstant));
ax += dx * f;
ay += dy * f;
az += dz * f;
}
}
massI.ax = ax;
massI.ay = ay;
massI.az = az;
}
return this;
}
}
/*
* Inputs for our nBodyProblem
*/
const g = 39.5;
const dt = 0.008; //0.005 years is equal to 1.825 days
const softeningConstant = 0.15;
const masses = [{
name: "Sun", //We use solar masses as the unit of mass, so the mass of the Sun is exactly 1
m: 1,
x: -1.50324727873647e-6,
y: -3.93762725944737e-6,
z: -4.86567877183925e-8,
vx: 3.1669325898331e-5,
vy: -6.85489559263319e-6,
vz: -7.90076642683254e-7
},
{
name: "Mercury",
m: 1.65956463e-7,
x: -0.346390408691506,
y: -0.272465544507684,
z: 0.00951633403684172,
vx: 4.25144321778261,
vy: -7.61778341043381,
vz: -1.01249478093275
},
{
name: "Venus",
m: 2.44699613e-6,
x: -0.168003526072526,
y: 0.698844725464528,
z: 0.0192761582256879,
vx: -7.2077847105093,
vy: -1.76778886124455,
vz: 0.391700036358566
},
{
name: "Earth",
m: 3.0024584e-6,
x: 0.648778995445634,
y: 0.747796691108466,
z: -3.22953591923124e-5,
vx: -4.85085525059392,
vy: 4.09601538682312,
vz: -0.000258553333317722
},
{
m: 3.213e-7,
name: "Mars",
x: -0.574871406752105,
y: -1.395455041953879,
z: -0.01515164037265145,
vx: 4.9225288800471425,
vy: -1.5065904473191791,
vz: -0.1524041758922603
}
];
/*
* Create an instance of the nBodyProblem with the inputs above
* We clone the masses array by parsing a stringified version of it so that we can reset the simulator with a minimum amount of fuss
*/
const innerSolarSystem = new nBodyProblem({
g,
dt,
masses: JSON.parse(JSON.stringify(masses)),
softeningConstant
});
/*
* Motion trails
*/
class Manifestation {
constructor(ctx, trailLength, radius) {
this.ctx = ctx;
this.trailLength = trailLength;
this.radius = radius;
this.positions = [];
}
storePosition(x, y) {
this.positions.push({
x,
y
});
if (this.positions.length > this.trailLength) this.positions.shift();
}
draw(x, y) {
this.storePosition(x, y);
const positionsLen = this.positions.length;
for (let i = 0; i < positionsLen; i++) {
let transparency;
let circleScaleFactor;
const scaleFactor = i / positionsLen;
if (i === positionsLen - 1) {
transparency = 1;
circleScaleFactor = 1;
} else {
transparency = scaleFactor / 2;
circleScaleFactor = scaleFactor;
}
this.ctx.beginPath();
this.ctx.arc(
this.positions[i].x,
this.positions[i].y,
circleScaleFactor * this.radius,
0,
2 * Math.PI
);
this.ctx.fillStyle = `rgb(0, 12, 153, ${transparency})`;
this.ctx.fill();
}
}
}
/*
* Get the canvas element and its context from the DOM
*/
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
/*
* Full screen action
*/
const width = (canvas.width = window.innerWidth);
const height = (canvas.height = window.innerHeight);
/*
* Animation constants
*
* scale is the number of pixels per astronomical units
*
* radius is the radius of the circle that represents the current position of a mass
*
* trailLength is the number of previous positions that we should draw in the motion trail
*/
const scale = 70;
const radius = 4;
const trailLength = 35;
/*
* Iterate over the masses being simulated and add a visual manifestation for each of them
*/
const populateManifestations = masses => {
masses.forEach(
mass =>
(mass["manifestation"] = new Manifestation(
ctx,
trailLength,
radius
))
);
};
populateManifestations(innerSolarSystem.masses);
/*
* Click the reset button to reset the simulation
*/
document.querySelector('#reset-button').addEventListener('click', () => {
innerSolarSystem.masses = JSON.parse(JSON.stringify(masses));
populateManifestations(innerSolarSystem.masses);
}, false);
/*
* Code for adding masses with you mouse
*/
//Step 1.
let mousePressX = 0;
let mousePressY = 0;
//Step 2.
let currentMouseX = 0;
let currentMouseY = 0;
//Step 3.
let dragging = false;
//Step 4.
canvas.addEventListener(
"mousedown",
e => {
mousePressX = e.clientX;
mousePressY = e.clientY;
dragging = true;
},
false
);
//Step 5
canvas.addEventListener(
"mousemove",
e => {
currentMouseX = e.clientX;
currentMouseY = e.clientY;
},
false
);
//Step 6
const massesList = document.querySelector("#masses-list");
canvas.addEventListener(
"mouseup",
e => {
const x = (mousePressX - width / 2) / scale;
const y = (mousePressY - height / 2) / scale;
const z = 0;
const vx = (e.clientX - mousePressX) / 35;
const vy = (e.clientY - mousePressY) / 35;
const vz = 0;
innerSolarSystem.masses.push({
m: parseFloat(massesList.value),
x,
y,
z,
vx,
vy,
vz,
manifestation: new Manifestation(ctx, trailLength, radius)
});
dragging = false;
},
false
);
/*
* The animate function that sets everything in motion.
* We run it 60 times a second with the help of requestAnimationFrame
*/
const animate = () => {
/*
* Advance our simulation by one step
*/
innerSolarSystem
.updatePositionVectors()
.updateAccelerationVectors()
.updateVelocityVectors();
/*
* Clear the canvas in preparation for the next drawing cycle
*/
ctx.clearRect(0, 0, width, height);
const massesLen = innerSolarSystem.masses.length;
/*
* Let us draw some masses!
*/
for (let i = 0; i < massesLen; i++) {
const massI = innerSolarSystem.masses[i];
/*
* The origin (x = 0, y = 0) of the canvas coordinate system is in the top left corner
* To prevent our simulation from being centered on the top left corner, include the x and y offsets
* So that it is centered smack in the middle of the canvas
*/
const x = width / 2 + massI.x * scale;
const y = height / 2 + massI.y * scale;
/*
* Draw our motion trail
*/
massI.manifestation.draw(x, y);
/*
* If the mass has a name, draw it onto the canvas next to the leading circle of the motion trail
*/
if (massI.name) {
ctx.font = "14px Arial";
ctx.fillText(massI.name, x + 12, y + 4);
ctx.fill();
}
/*
* Stop masses from escaping the bounds of the viewport
* If either condition is met, the velocity of the mass will be reversed
* And the mass will bounce back into the inner solar system
*/
if (x < radius || x > width - radius) massI.vx = -massI.vx;
if (y < radius || y > height - radius) massI.vy = -massI.vy;
}
/*
* Draw the line which indicates direction and velocity of a mass that is about to be added when the mouse is being dragged
*/
if (dragging) {
ctx.beginPath();
ctx.moveTo(mousePressX, mousePressY);
ctx.lineTo(currentMouseX, currentMouseY);
ctx.strokeStyle = "red";
ctx.stroke();
}
requestAnimationFrame(animate);
};
animate();
Also see: Tab Triggers