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.
<h1>React Canvas Component</h1>
<p>
CanvasComponent is a React component for doing raw HTML5 canvas drawing. It ties into life-cycle methods, to allow for proper timing of DOM loading and triggering of updates, but it exposes these as functions through the props `init` and `draw`.
</p>
<pre><code><CanvasComponent
width={400}
height={400}
init={(canvas, ctx, props) => …}
draw={(canvas, ctx, props) => …}
…
/></code></pre>
<p>
The `init` function (if present) is only called once when the component mounts, and the `draw` function is called every time any of the props to `CanvasComponent` update. Both are passed the Canvas DOM element, the 2d context, and all of the props that the CanvasComponent received.
</p>
<p>
It even handles high pixel density screens automatically, by auto-sizing and scaling the canvas to match the screen. Take a look at the JS code to see how it works.
</p>
<p>
<strong>Demo - Conway’s Game of Life:</strong>
</p>
<p>
Take a look at the demo code to see `CanvasComponent` in action.
</p>
<div id="root"></div>
html, body {
margin: 0;
padding: 0;
}
body {
font: normal 14px/20px Helvetica Neue, Helvetica, Arial, sans-serif;
max-width: 630px;
margin: 2em auto;
padding: 0 15px;
}
h1 {
font-size: 30px;
line-height: 40px;
}
h1, p, pre {
margin: 0 0 20px;
}
pre {
padding: 20px;
background: #f0f0f0;
border-radius: 2px;
}
canvas {
background: #00bcd4;
margin-bottom: 60px;
}
// ## Canvas Component
//
// A React Component abstraction for doing raw HTML5 canvas
// rendering in React
// Codepen doesn't do es6 imports...
// import React, { PureComponent } from 'react';
// import ReactDOM from 'react-dom';
// import PropTypes from 'prop-types';
const { PureComponent } = React;
const { render } = ReactDOM;
// Component
class CanvasComponent extends PureComponent {
constructor(props) {
super(props);
this.canvasRef = React.createRef();
// https://www.html5rocks.com/en/tutorials/canvas/hidpi/
this.canvasRatio = window.devicePixelRatio || 1;
}
// Life-cycle
componentDidMount() {
this._initCanvas();
this._drawCanvas();
}
componentDidUpdate() {
this._drawCanvas();
}
// Helpers
_initCanvas() {
const canvasElt = this.canvasRef.current;
if (canvasElt) {
const ctx = canvasElt.getContext("2d");
ctx.scale(this.canvasRatio, this.canvasRatio);
if (this.props.init) {
this._frame(() => {
this.props.init(canvasElt, ctx, this.props);
});
}
}
}
_drawCanvas() {
const canvasElt = this.canvasRef.current;
if (canvasElt) {
const ctx = canvasElt.getContext("2d");
if (this.props.draw) {
this._frame(() => {
this.props.draw(canvasElt, ctx, this.props);
});
}
}
}
_frame = (fn) => window.requestAnimationFrame(fn);
// Render
render() {
const { width, height } = this.props;
const style = {
width: `${width}px`,
height: `${width}px`
};
return (
<canvas
ref={this.canvasRef}
width={width * this.canvasRatio}
height={height * this.canvasRatio}
style={style}
/>
);
}
}
CanvasComponent.propTypes = {
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
init: PropTypes.func,
draw: PropTypes.func
};
//
// ## Demo
//
// ### Life Model
//
// Abstraction for the state of Conway's Game of Life
//
const LifeModel = (function () {
const ALIVE = true;
const DEAD = false;
const self = {
create: (width, height) => {
const positions = [];
for (let y = 0; y < height; y++) {
let row = [];
for (let x = 0; x < width; x++) {
row.push(parseInt(Math.random() * 2) === 0 ? ALIVE : DEAD);
}
positions.push(row);
}
return positions;
},
step: (positions, width, height) => {
let newPositions = [];
for (let y = 0; y < height; y++) {
let newRow = [];
newPositions.push(newRow);
for (let x = 0; x < width; x++) {
let isAlive = self.isAlive(positions, x, y);
let count = self._countNeighbors(positions, x, y);
if (isAlive) {
newRow.push(count === 2 || count === 3 ? ALIVE : DEAD);
} else {
newRow.push(count === 3 ? ALIVE : DEAD);
}
}
}
return newPositions;
},
isAlive: (positions, x, y) => positions[y] && positions[y][x] === ALIVE,
_countNeighbors: (positions, x, y) => {
let count = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
if (!(i === 0 && j === 0) && self.isAlive(positions, x + j, y + i)) {
count += 1;
}
}
}
return count;
}
};
return self;
})();
// ### Life Component
//
// A simple component to render Conway's Game of Life
// using LifeModel and CanvasComponent.
//
class LifeComponent extends React.Component {
constructor(props) {
super(props);
const width = 100;
const height = 100;
const positions = LifeModel.create(width, height);
this.state = { width, height, positions, paused: true };
}
// Life-cycle
componentDidMount() {
if (!this.state.paused) {
this._start();
}
}
componentWillUnmount() {
this._pause();
}
// Helpers
_start() {
this.setState({ paused: false });
const loop = () => {
window.clearTimeout(this._timeout);
this._timeout = window.setTimeout(() => {
let { positions, width, height } = this.state;
let nextPositions = LifeModel.step(positions, width, height);
this.setState({ positions: nextPositions });
loop();
}, 150);
};
loop();
}
_pause() {
this.setState({ paused: true });
window.clearTimeout(this._timeout);
}
// Render
render() {
const { width, height, positions, paused } = this.state;
const zoom = 4;
const clickToggle = () => (paused ? this._start() : this._pause());
const style = { cursor: "pointer", display: "inline-block" };
return (
<div style={style} onClick={clickToggle}>
<CanvasComponent
width={width * zoom}
height={height * zoom}
init={init}
draw={draw}
positions={positions}
zoom={zoom}
paused={paused}
/>
</div>
);
}
}
// ### Canvas Component Functions
const init = (canvas, ctx, props) => {};
const draw = (canvas, ctx, props) => {
const { width, height, zoom, positions, paused } = props;
const gameWidth = width / zoom;
const gameHeight = height / zoom;
ctx.save();
ctx.scale(zoom, zoom);
ctx.clearRect(0, 0, gameWidth, gameHeight);
ctx.fillStyle = "#000";
for (let y = 0; y < gameHeight; y++) {
for (let x = 0; x < gameWidth; x++) {
if (LifeModel.isAlive(positions, x, y)) {
ctx.fillRect(x, y, 1, 1);
}
}
}
ctx.restore();
if (paused) {
const fontSize = Math.min(width, height) / 9;
ctx.fillStyle = "#fff";
ctx.strokeStyle = "#000";
ctx.lineWidth = Math.max(1, fontSize / 10);
ctx.font = `${fontSize}px impact`;
const text = "Click to Start";
const x = (width - ctx.measureText(text).width) / 2;
const y = (height + fontSize) / 2;
ctx.strokeText(text, x, y);
ctx.fillText(text, x, y);
}
};
//
render(<LifeComponent />, document.getElementById("root"));
Also see: Tab Triggers