Canvas

Drawing to the screen using the Canvas API

nx.js does not implement a full DOM for rendering content to the screen. Instead, it offers the more low-level Canvas API which allows your application to draw to the screen.

The global screen object is used to create a CanvasRenderingContext2D instance, at which point the app is in canvas rendering mode.

You should avoid using any console printing functions when in canvas rendering mode. Doing so will change the app back to console rendering mode.

Example

Let's draw a simple house with the Canvas API:

// Creating the canvas context enters "canvas rendering" mode
const ctx = screen.getContext('2d');
 
// The default background color is black, so draw the house as white
ctx.fillStyle = 'white';
ctx.strokeStyle = 'white';
 
// Set line width
ctx.lineWidth = 10;
 
// Wall
ctx.strokeRect(75, 140, 150, 110);
 
// Door
ctx.fillRect(130, 190, 40, 60);
 
// Roof
ctx.beginPath();
ctx.moveTo(50, 140);
ctx.lineTo(150, 60);
ctx.lineTo(250, 140);
ctx.closePath();
ctx.stroke();

This example was adapted from the MDN Canvas tutorial.

Using React

The Canvas API is a low-level API, and it's not very well suited to building complex UIs. However, it can be used to build simple UIs, and it's also possible to use React with the Canvas API.

To use React with the Canvas API, you'll need to use a library like react-canvas.

Here's an example of a simple React app that uses the Canvas API:

import React from 'react';
import ReactDOM from 'react-dom';
import Canvas from 'react-canvas';
 
class App extends React.Component {
  render() {
    return (
      <Canvas
        width={300}
        height={300}
        style={{ border: '1px solid black' }}
 
## Cards
 
<Cards>
  <Card title="Learn about rendering to the screen using React" href="/docs/react" />
  <Card title="Learn about using custom fonts with the Canvas API" href="/docs/web/fonts" />
</Cards>

On this page