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="perspectiveCont">
<div class="grid js-landscape">
</div>
</div>
<p class="label--dragInstruct js-label--dragInstruct">Drag to rotate freely</p>
<p class="label--generating js-label--generating active">Generating...</p>
<div class="mouseZone js-mouseZone">
</div>
<p class="credit">
<a href="https://www.twitter.com/sebastianlenton" target="_blank">
@sebastianlenton
</a>
</p>
/********************************************************
Div rotatable with mouse when button held down
********************************************************/
//so using a CSS custom property on a linear gradient background on a transformed element seems to absolutely tank the frame rate! So I removed all background colour custom properties...
//doesn't seem to make a difference to rotation of the base grid though (the units are being rotated via injection of an inline style anyway).
$backgroundBlue: 25; //blue component of background/div gradient/base
$backgroundRGB: rgb(0,0,$backgroundBlue);
$backgroundRGBA-zero: rgba(0,0,$backgroundBlue, 0);
* {
box-sizing: border-box;
}
html, body {
height: 100%;
overflow: hidden;
}
body {
margin: 0;
background: linear-gradient(darken( blue, 10% ), darken( $backgroundRGB, 0% ), darken( $backgroundRGB, 3% ));
overflow: hidden;
}
p {
background: rgba(0,0,0,0.3);
padding: 1rem;
color: white;
font-family: sans-serif;
position: absolute;
transform: translate(-50%, -50%);
z-index: 2;
line-height: 0;
user-select: none;
opacity: 1;
transition: opacity 1.5s;
&.fadeOut {
opacity: 0;
}
}
.label--dragInstruct {
top: 75%;
left: 50%;
}
.label--generating {
display: none;
top: 50%;
left: 50%;
&.active {
display: block;
}
}
.perspectiveCont {
perspective: 2500px;
top: 0;
left: 0;
height: 100%;
}
.grid {
$maxWidth: 50rem;
$maxHeight: 50rem;
--rotX: 50deg;
--rotY: 0deg;
--rotZ: 45deg;
/** background */
background-color: $backgroundRGB;
/** dimensions */
width: 70vh;
height: 70vh;
max-width: $maxWidth;
max-height: $maxHeight;
/** position */
position: absolute;
z-index: 1;
top: 50vh;
left: 50%;
transform: translate(-50%, -50%) rotateX(var(--rotX)) rotateY(var(--rotY)) rotateZ(var(--rotZ));
transform-style: preserve-3d;
transform-origin: center center;
}
.landscape__unit {
position: absolute;
transform-origin: top;
//using a custom property in a linear gradient on transformed elements seems to absolutely tank the frame rate!
background-image: linear-gradient(
180deg, $backgroundRGB, $backgroundRGBA-zero
);
}
.mouseZone {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 3;
}
/* GUI */
.dg.ac {
z-index: 5 !important;
}
/** credit **/
.credit {
padding: 0;
position: absolute;
bottom: 1.5rem;
right: 1rem;
margin-bottom: 0;
font-weight: bold;
text-shadow: .1rem .1rem 0 darken(#84AFC8,25%);
font-size: 1.2rem;
z-index: 999;
transform: none;
a {
color: white;
text-decoration: none;
display: block;
transition: transform .25s;
transform: scale(1);
&:hover {
transform: scale(1.2) translate(-.75rem, -.15rem);
}
}
}
/********************************************************
Perlin Noise Landscape Generator
By Sebastian Lenton
Depends on https://github.com/josephg/noisejs (see settings)
22/08/19
This assumes all maps will be square
Think the library outputs between -.6 and .6 I think (if you see any weird results then this is incorrect!)
********************************************************/
/********************************************************
2d noise map output
********************************************************/
var PerlinNoiseGenerator = function() {
this.seed = 49
this.zoom = 3.8; //zoom subtracted from map start (0) and map end (mapSizeMax), so can't be more than mapSizeMax / 2
this.resolution = 24;
this.lastSeed = this.seed; //this is to do with DAT.gui- to prevent a reseed if the same value gets entered (the change event fires if you even click into the field...)
this.lastZoom = this.zoom;
this.lastResolution = this.resolution;
this.mapSizeMax = 10; //map runs from 0 to 10
this.mapData = [];
//"check has changed" functions- prob better/less repetitive ways to do these
//again, this is to stop DAT.gui triggering an update if the value hasn't actually changed
this.checkSeedHasChanged = function() {
if(this.seed != this.lastSeed) {
this.lastSeed = this.seed;
return true;
}
return false;
}
this.checkZoomHasChanged = function() {
if(this.zoom != this.lastZoom) {
this.lastZoom = this.zoom;
return true;
}
return false;
}
this.checkResolutionHasChanged = function() {
if(this.resolution != this.lastResolution) {
this.lastResolution = this.resolution;
return true;
}
return false;
}
//return an array containing a noise map
this.outputMap = function() {
this.mapData = [];
//clamp zoom if bigger than workable
if(this.zoom >= this.mapSizeMax / 2) {
this.zoom = this.mapSizeMax / 2;
}
noise.seed(this.seed);
var mapSize = (this.mapSizeMax - this.zoom) - (0 + this.zoom);
var units = mapSize / this.resolution;
for(var q=0;q<this.resolution;q++) {
var mapRow = [];
for(var r=0;r<this.resolution;r++) {
var currentValue = noise.perlin2(
(q * units) - (mapSize / 2),
(r * units) - (mapSize / 2),
);
mapRow.push(currentValue);
}
this.mapData.push(mapRow);
}
}
}
/********************************************************
Landscape Div Output
********************************************************/
var LandscapeDOM = function() {
this.elm = document.querySelector('.js-landscape');
this.rotX = 0;
this.rotY = 0;
this.rotZ = 0;
this.map = [];
this.minMaxRot = 60; //the min or max rotation allowed on the X axis
//stuff to do with autorotate
this.autoRotate = true;
this.timer;
this.autoRotSpeed = 18/1000; //degrees per second
this.lastFrame = 0;
this.elmLabelGenerating = document.querySelector('.js-label--generating');
//copy in a perlin noise map array
//hmm, does it actually need to make its own copy, given (in the current implementation) the map is just being read from, not changed?
this.loadMap = function(arrMap) {
this.map = [];
for (var m = 0; m < arrMap.length; m++) {
var mapRow = [];
for (var n = 0; n < arrMap[0].length; n++) {
var valToCopy = arrMap[m][n];
mapRow.push(valToCopy);
}
this.map.push(mapRow);
}
}
//clear map child divs
this.deleteDivs = function() {
while (this.elm.firstChild) {
this.elm.removeChild(this.elm.firstChild);
}
}
//create the divs within the map
this.createDivs = function() {
for (var m = 0; m < this.map.length; m++) {
for (var n = 0; n < this.map[0].length; n++) {
var newLandscapeUnit = document.createElement('div');
newLandscapeUnit.classList.add('landscape__unit', 'js-landscape__unit');
this.elm.appendChild(newLandscapeUnit);
}
}
}
//set styles for each div (dimensions, colour, position- not setting transform here)
this.setStyles = function() {
var divs = document.querySelectorAll('.js-landscape__unit');
var widthMod = 1; //tweak the width of each elem to cover up the gaps (or show them). Not bothering as I like the gaps, plus it affects the mid placement of the elemns atm (should fix but CBA right now)
var counter = 0;
var perlinMinMax = .55; //roughly the min/max value of the library- I think!
for (var m = 0; m < this.map.length; m++) {
for (var n = 0; n < this.map[0].length; n++) {
divs[counter].style.width = ( 100 / this.map.length ) * widthMod + '%';
divs[counter].style.top = ((100 / this.map.length) * m) + ((100 / this.map.length / 2)) + '%';
divs[counter].style.left = ((100 / this.map.length) * n) + '%';
//set height- need to ensure it's not negative, or value from prev seed would be re-used (when seed gets changed)
var height = (this.map[n][m] + perlinMinMax) * 50;
if(height <= 0) {
height = 0;
}
divs[counter].style.height = height + '%';
//set background colour
var bgColor = Math.round(((this.map[n][m] + perlinMinMax) * 255));
if(bgColor > 255) {
bgColor = 255;
}
divs[counter].style.backgroundColor = 'rgb(' + bgColor + ',0,70)';
counter++;
}
}
}
//set initial rot values
this.initRot = function() {
var elmStyles = getComputedStyle(this.elm);
this.rotX = parseInt(elmStyles.getPropertyValue('--rotX').trim());
this.rotY = parseInt(elmStyles.getPropertyValue('--rotY').trim());
this.rotZ = parseInt(elmStyles.getPropertyValue('--rotZ').trim());
}
//update rotation values of rect by incrememting
this.updateInc = function(rotX, rotY, rotZ) {
this.rotX += rotX;
this.rotY += rotY;
this.rotZ += rotZ;
//clamp values (90 being the centre value)
var degCentre = 90;
//Upper:
if(this.rotX > degCentre + this.minMaxRot ) {
this.rotX = degCentre + this.minMaxRot;
}
//Lower:
if(this.rotX < degCentre - this.minMaxRot) {
this.rotX = degCentre - this.minMaxRot;
}
}
//update the rotation CSS values themselves
this.updateCSS = function() {
this.elm.style.setProperty('--rotX', this.rotX + 'deg');
this.elm.style.setProperty('--rotY', this.rotY + 'deg');
this.elm.style.setProperty('--rotZ', this.rotZ + 'deg');
}
//counter rotate the child elements
//this also has to be called when a new map gets generated
this.updateChildren = function() {
var children = document.querySelectorAll('.js-landscape__unit');
var thisRotZ = this.rotZ;
children.forEach(function(item) {
item.style.transform = 'rotatex(90deg) rotatey(' + ( thisRotZ * -1) + 'deg)';
});
}
//autorotate animation
this.autorotate = function() {
if(this.autoRotate) {
var thisFrameTime = performance.now();
this.updateInc(0,0,this.autoRotSpeed * (thisFrameTime - this.lastFrame));
this.lastFrame = thisFrameTime;
this.updateCSS();
this.updateChildren();
window.requestAnimationFrame(this.autorotate.bind(this)); //https://stackoverflow.com/questions/6065169/requestanimationframe-with-this-keyword
}
}
this.autorotateOn = function() {
this.autoRotate = true;
}
this.autorotateOff = function() {
this.autoRotate = false;
}
//show or hide "regenerating" label
//true to show, false to hide
this.showLabelGenerating = function(showHide) {
var classShowerHider = 'active';
if(showHide) {
this.elmLabelGenerating.classList.add(classShowerHider);
} else {
this.elmLabelGenerating.classList.remove(classShowerHider);
}
}
}
/********************************************************
Mouse Listener for dragging of LandscapeDiv
********************************************************/
var MouseListener = function(rotRect, instruction) {
this.elm = document.querySelector('.js-mouseZone');
this.mouseX;
this.mouseY;
this.mouseXLast;
this.mouseYLast;
this.deltaX;
this.deltaY;
this.rotRect = rotRect; //the div to rotate
this.rotDampen = 4; //how much to dampen rotation by (X only I think?)
this.instruction = instruction; //the p saying "drag to rotate"
//set values to initial ones
this.initValues = function() {
this.mouseX = false;
this.mouseY = false;
this.mouseXLast = false;
this.mouseYLast = false;
this.deltaX = 0;
this.deltaY = 0;
}
//update values
this.update = function(newMouseX, newMouseY) {
this.mouseXLast = this.mouseX;
this.mouseYLast = this.mouseY;
this.mouseX = newMouseX;
this.mouseY = newMouseY;
//if no values are false, there are at least two frames of movement (current and previous) so we can calculate a delta
//otherwise set deltas to 0 (or else it will jerk around on drag start)
if(this.mouseX && this.mouseXLast && this.mouseY && this.mouseYLast ) {
this.deltaX = this.mouseX - this.mouseXLast;
this.deltaY = this.mouseY - this.mouseYLast;
} else {
this.deltaX = 0;
this.deltaY = 0;
}
}
//do some normalisation on the deltas to reverse the drag direction, make it a bit slower etc
this.normaliseDeltas = function() {
this.deltaX = ( this.deltaX * -1 );
this.deltaY = ( this.deltaY * -1 );
this.deltaX = this.deltaX / this.rotDampen;
this.deltaY = this.deltaY / this.rotDampen;
}
//add the event listeners to enable control
this.addMouseListener = function() {
//copy over the ref to this and this's element (as I'm a dumbass who can't program properly)
var that = this;
var thatElm = this.rotRect;
//mouse control
if(this.elm !== null) {
this.elm.addEventListener('mousemove', function(e) {
if(e.buttons === 1) {
that.update(e.clientX, e.clientY);
that.normaliseDeltas();
thatElm.updateInc(that.deltaY, 0, that.deltaX);
thatElm.updateCSS();
thatElm.updateChildren();
}
});
this.elm.addEventListener('mousedown', function(e) {
e.preventDefault(); //prevent selection etc
that.initValues();
thatElm.autorotateOff();
that.instruction.classList.add('fadeOut');
});
//touch control
this.elm.addEventListener('touchmove', function(e) {
e.preventDefault(); //prevent iOS scrolling
that.update(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
that.normaliseDeltas();
thatElm.updateInc(that.deltaY, 0, that.deltaX);
thatElm.updateCSS();
thatElm.updateChildren();
});
this.elm.addEventListener('touchstart', function(e) {
e.preventDefault(); //prevent selection etc
thatElm.autoRotate = false;
that.initValues();
that.instruction.classList.add('fadeOut');
});
}
}
//switch mouse zone on and off
//this is to disable mouse rotation when starting a click in DAT.gui and moving off (otherwise it starts rotating the element, and it all looks a bit crap)
this.mouseZoneOff = function() {
this.elm.style.display = 'none';
}
this.mouseZoneOn = function() {
this.elm.style.display = 'block';
}
}
/********************************************************
Main
********************************************************/
var noiseGenerator = new PerlinNoiseGenerator();
noiseGenerator.outputMap();
var landscapeDOM = new LandscapeDOM();
landscapeDOM.initRot();
landscapeDOM.loadMap(noiseGenerator.mapData);
landscapeDOM.createDivs();
landscapeDOM.setStyles();
landscapeDOM.showLabelGenerating(false);
landscapeDOM.updateChildren();
landscapeDOM.autorotate();
var mouseListener = new MouseListener(landscapeDOM, document.querySelector('.js-label--dragInstruct'));
mouseListener.addMouseListener();
/********************************************************
Controls for GUI in top right (uses DAT.gui)
********************************************************/
var gui = new dat.GUI();
var seedChange = gui.add(noiseGenerator, 'seed', 0, 65535).step(1);
var zoomChange = gui.add(noiseGenerator, 'zoom', .1, 5);
var resolutionChange = gui.add(noiseGenerator, 'resolution', 1, 70).step(1);
//hmm, seems like we have to duplicate code for these- is there a better way?
seedChange.onChange(function(value) {
landscapeDOM.showLabelGenerating(true);
mouseListener.mouseZoneOff();
});
zoomChange.onChange(function(value) {
landscapeDOM.showLabelGenerating(true);
mouseListener.mouseZoneOff();
});
resolutionChange.onChange(function(value) {
landscapeDOM.showLabelGenerating(true);
mouseListener.mouseZoneOff();
});
seedChange.onFinishChange(function(value) {
if( noiseGenerator.checkSeedHasChanged() ) {
noiseGenerator.outputMap();
landscapeDOM.loadMap(noiseGenerator.mapData);
landscapeDOM.setStyles();
landscapeDOM.updateChildren();
landscapeDOM.autorotateOn();
landscapeDOM.autorotate();
}
mouseListener.mouseZoneOn();
landscapeDOM.showLabelGenerating(false);
});
zoomChange.onFinishChange(function(value) {
if( noiseGenerator.checkZoomHasChanged() ) {
noiseGenerator.outputMap();
landscapeDOM.loadMap(noiseGenerator.mapData);
landscapeDOM.setStyles();
landscapeDOM.updateChildren();
}
mouseListener.mouseZoneOn();
landscapeDOM.showLabelGenerating(false);
});
resolutionChange.onFinishChange(function(value) {
if( noiseGenerator.checkResolutionHasChanged() ) {
noiseGenerator.outputMap();
landscapeDOM.loadMap(noiseGenerator.mapData);
landscapeDOM.deleteDivs();
landscapeDOM.createDivs();
landscapeDOM.setStyles();
landscapeDOM.updateChildren();
}
mouseListener.mouseZoneOn();
landscapeDOM.showLabelGenerating(false);
});
Also see: Tab Triggers