Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

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.

+ add another resource

Packages

Add Packages

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.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <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>&ltCanvasComponent
  width={400}
  height={400}
  init={(canvas, ctx, props) => …}
  draw={(canvas, ctx, props) => …}
  …
  /&gt</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>
              
            
!

CSS

              
                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;
}
              
            
!

JS

              
                // ## 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"));

              
            
!
999px

Console