nx.js

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 may be used to create a CanvasRenderingContext2D instance, at which point the app is considered to be in canvas rendering mode.

Important

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

This example was adapted from the MDN Canvas tutorial.

Let's draw a simple house to the screen by using the Canvas API:

src/main.ts
// 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();
Screenshot

Using React

One of the original goals of nx.js was to be able to render homebrew applications using React.

To achieve that goal, react-tela was created which uses the Canvas API to render the application's UI. react-tela is compatible with web browsers and Node.js, but was specifically designed to work with nx.js.

Example

import React, { useState, useEffect } from 'react';
import { Rect } from 'react-tela';
import { render } from 'react-tela/render';
 
function App() {
	const [rotate, setRotate] = useState(0);
 
    useEffect(() => {
        let id: number;
        function update() {
            id = requestAnimationFrame(update);
            setRotate(r => r + 1);
        }
        update();
        return () => cancelAnimationFrame(id);
    }, []);
 
	return (
		<Rect
			fill='green'
			rotate={rotate}
			width={100}
			height={70}
			x={200}
			y={200}
		/>
	);
}
 
render(<App />, screen);

Learn more

On this page