Skip to content

Pixels

Animated Pixel Display

This example demonstrates how to create an animated pixel display using NumPy arrays and colight.plot.

First, let's import the required libraries:

Generate Pixels

The generate_pixels function creates animated RGB frames using phase-shifted circular waves, returning a uint8 numpy array.

Plot a Single Frame

Let's start by plotting a single frame of our pixel data. We'll use Plot.pixels to display the RGB values:

Generate a single frame

Plot it using Plot.pixels

Plot.pixels(single_frame, imageWidth=50, imageHeight=50)

Create Interactive Display

Now let's set up the visual with animation controls. We manage the state using Plot.initialState, which creates a shared state object accessible from both Python and JavaScript. The state contains our pixel data array, dimensions, current frame index, and animation speed. The Plot.pixels component reads the current frame from state using js("$state.pixels[$state.frame]"), while the slider component updates the frame index in state as it moves. This state-driven approach allows smooth coordination between the display and controls.

(
    plot := (
        Plot.initialState(
            {"pixels": data, "width": width, "height": height, "frame": 0, "fps": fps}
        )
        | Plot.pixels(
            js("$state.pixels[$state.frame]"),
            imageWidth=js("$state.width"),
            imageHeight=js("$state.height"),
        )
        | Plot.Slider(
            "frame",
            rangeFrom=js("$state.pixels"),
            controls=["play", "fps"],
            fps=js("$state.fps"),
        )
    )
)
plot.state.update(
    {"pixels": generate_pixels(500, 500, 60, linear=True), "width": 500, "height": 500}
)

Plot.bitmap

Instead of rendering pixels within an Observable Plot canvas, we can render them to an html canvas as a bitmap image.

Plot.bitmap(single_frame, width, height)