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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Горящий корабль</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="animationCanvas" width="600" height="600"></canvas>
<form id="configForm">
<label for="xRangeStart">x_range: </label>
<input type="number" id="xRangeStart" step="any" placeholder="Start">
<input type="number" id="xRangeEnd" step="any" placeholder="End"><br><br>
<label for="yRangeStart">y_range: </label>
<input type="number" id="yRangeStart" step="any" placeholder="Start">
<input type="number" id="yRangeEnd" step="any" placeholder="End"><br><br>
<button type="button" id="changeConfigBtn">Изменить конфигурацию</button>
<button type="button" id="resetFormBtn">Сбросить конфигурацию</button>
</form>
<div class="description">
<p><strong>Полный обзор фрактала:</strong> x_range [-2.2, 2.2], y_range [-2.2, 2.2]</p>
<p><strong>Увеличение левого нижнего угла:</strong> x_range [-1.81, -1.39], y_range [-0.32, 0.03]</p>
<p><strong>Корабль с двумя большими мачтами:</strong> x_range [-1.65, -1.58], y_range [-0.074, 0.018]</p>
<p><strong>Маленький кораблик:</strong> x_range [-1.948, -1.925], y_range [-0.0095, 0.003]</p>
<p><strong>Самый большой корабль:</strong> x_range [-1.8, -1.7], y_range [-0.08, 0.01]</p>
<p><strong>Мачты:</strong> x_range [-1.7825, -1.765], y_range [-0.0671, -0.0494]</p>
<p><strong>Горящая полоса:</strong> x_range [-2.01, -1.9469], y_range [-0.02, 0.02]</p>
</div>
<script src="app.js"></script>
</body>
</html>
body, html {
margin: 0;
padding: 0;
height: 100%;
background-color: #293133;
}
#animationCanvas {
display: block;
margin-left: 20px;
margin-top: 20px;
position: absolute;
top: 0;
left: 0;
width: 50%;
height: 75%;
background-color: black;
}
#configForm {
position: absolute;
top: 3%;
left: 55%;
transform: translate(0%, 0%);
background-color: rgba(255, 255, 255, 0.8);
padding: 20px;
border-radius: 10px;
}
.description{
position: absolute;
top: 30%;
left: 55%;
transform: translate(0%, 0%);
background-color: rgba(255, 255, 255, 0.8);
padding: 20px;
border-radius: 10px;
font-size: 14px;
color: #293133;
}
var canvas = document.getElementById("animationCanvas");
var ctx = canvas.getContext("2d");
// Задать максимальное количество итераций и радус выхода для
// заполнения фона вне фрактала
const MAX_ITERATIONS = 255;
const ESCAPE_RADIUS = 2;
const ESCAPE_THRESHOLD = ESCAPE_RADIUS * ESCAPE_RADIUS;
// Ширина и высота холста
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
function iterateUntilEscape(x0, y0) {
/**
* Функция, которая задает радиус изменения цветов
* при отрисовке фрактала на холсте (не более MAX_ITERATIONS раз).
*
* Основывается на стартовой точке рисования.
*
* Возвращает массив с количеством пройденных итераций и радиусом выхода.
*/
let x = 0, y = 0;
let iteration = 0;
while ((x*x + y*y < ESCAPE_THRESHOLD) && (iteration < MAX_ITERATIONS)) {
const x_n = x*x - y*y + x0;
const y_n = 2 * Math.abs(x*y) + y0;
x = x_n;
y = y_n;
iteration++;
}
return [iteration, Math.sqrt(x*x + y*y)];
}
function getMu(numIterations, escapeDistance) {
/**
* Нормализация количества итераций на основе расстояния выхода
* для получения более плавной картинки
*/
return numIterations + 1 - Math.log2(Math.log(escapeDistance));
}
function getColor(mu){
/**
* Задать цвет для пикселя
*/
return [ 255, mu * 7, 0, mu * 15 ]
}
function drawBurningShip(xRange, yRange, colorFunc) {
const canvasImageData = ctx.createImageData(canvasWidth, canvasHeight);
const image = canvasImageData.data;
for (let i = 0; i < canvasHeight; i++) {
for (let j = 0; j < canvasWidth; j++) {
// Начальное комплексное число
const x0 = xRange[0] + j*(xRange[1] - xRange[0]) / canvasWidth;
const y0 = yRange[0] + i*(yRange[1] - yRange[0]) / canvasHeight;
// Получить количество итераций, пройденных в ходе изменения
// начального комплексного числа, а также расстояние выхода
// (область отрисовки)
const [numIterations, escapeDistance] = iterateUntilEscape(x0, y0);
// получить индекс текущего пикселя, который нужно закрасить
const pixelIndex = 4*i*canvasWidth + 4*j;
// "Плавно" закрашивать пиксели полученным цветом
if (numIterations !== MAX_ITERATIONS) {
const mu = getMu(numIterations, escapeDistance);
const pixels = colorFunc(mu);
for (let p = 0; p < 4; p++) {
image[pixelIndex + p] = pixels[p];
}
}
}
}
// Отобразить пиксель на холсте
ctx.putImageData(canvasImageData, 0, 0);
}
// Значения промежутков x и y по умолчанию
var x_range = [-1.8, -1.7];
var y_range = [-0.08, 0.01];
drawBurningShip(x_range, y_range, getColor);
function changeConfiguration() {
/**
* Функция считывает новые значения промежутков для x и y,
* которые пользователь указывает в полях для ввода, и
* перерисовывает фрактал
*/
var xStart = parseFloat(document.getElementById('xRangeStart').value);
var xEnd = parseFloat(document.getElementById('xRangeEnd').value);
var yStart = parseFloat(document.getElementById('yRangeStart').value);
var yEnd = parseFloat(document.getElementById('yRangeEnd').value);
drawBurningShip([xStart, xEnd], [yStart, yEnd], getColor);
}
// Получаем кнопку и добавляем обработчик события
// Применяет введенные пользователем значения
var changeConfigBtn = document.getElementById('changeConfigBtn');
changeConfigBtn.addEventListener('click', changeConfiguration);
// Функция для сброса формы
function resetForm() {
document.getElementById('configForm').reset();
}
// Получаем кнопку для сброса формы и добавляем обработчик события
// Сбрасываем указанные данные в полях ввода (не сбрасывает фрактал до
// состояния по умолчанию)
var resetFormBtn = document.getElementById('resetFormBtn');
resetFormBtn.addEventListener('click', resetForm);
Also see: Tab Triggers