### Development Installation of ipycanvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/installation.md Steps for a development installation, including cloning the repository, installing the package in editable mode, and setting up the JupyterLab extension. ```bash git clone https://github.com/jupyter-widgets-contrib/ipycanvas.git cd ipycanvas pip install -e . ``` ```bash jupyter labextension develop . --overwrite jlpm run build ``` -------------------------------- ### Initializing the canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/animation.ipynb Setup for the canvas object with specific dimensions and styling. ```python size = 1000 canvas = Canvas(width=size, height=size) canvas.fill_style = "#fcba03" canvas ``` -------------------------------- ### Initialize batch API Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/offscreen_canvas.ipynb Setup canvas and generate random data for batch rendering operations. ```python # batch api shape = (1000,500) canvas = Canvas(width=shape[0], height=shape[1], layout=dict(width="100%")) await canvas.display() n = 100 # random colors rgb = np.random.randint(0, 255, size=(n, 3), dtype=np.uint8) # random positions x = np.random.randint(0, shape[0], size=n) y = np.random.randint(0, shape[1], size=n) ``` -------------------------------- ### Initialize ipycanvas environment Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/offscreen_canvas.ipynb Setup environment variables and imports required for ipycanvas functionality. ```python from math import pi import time import os import numpy as np os.environ['IPYCANVAS_DISABLE_OFFSCREEN_CANVAS'] = '0' from ipycanvas.compat import Canvas from ipycanvas.call_repeated import set_render_loop ``` -------------------------------- ### Initialize canvas for arc drawing Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/drawing_paths.md Setup code for drawing arcs on a canvas. ```python from math import pi from ipycanvas import Canvas canvas = Canvas(width=200, height=200) ``` -------------------------------- ### Install ipycanvas via pip Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/README.md Standard installation command for ipycanvas and the orjson dependency. ```bash pip install ipycanvas orjson ``` -------------------------------- ### Install ipycanvas using pip Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/installation.md Use this command to install the ipycanvas package with pip. ```bash pip install ipycanvas ``` -------------------------------- ### Install ipycanvas for JupyterLab 2 or older Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/README.md Required steps for legacy JupyterLab environments, including installing yarn and the extension manager. ```bash conda install -c conda-forge yarn jupyter labextension install @jupyter-widgets/jupyterlab-manager ipycanvas ``` -------------------------------- ### Set Rough Fill Styles Source: https://context7.com/jupyter-widgets-contrib/ipycanvas/llms.txt Demonstrates setting different rough fill styles for shapes. Requires ipycanvas to be installed. ```python canvas.rough_fill_style = "cross-hatch" canvas.fill_style = "orange" canvas.fill_rect(150, 150, 100, 80) canvas.rough_fill_style = "zigzag" canvas.fill_style = "purple" canvas.fill_rect(270, 150, 100, 80) ``` -------------------------------- ### Install ipycanvas via conda Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/README.md Installation command using the conda-forge channel. ```bash conda install -c conda-forge ipycanvas ``` -------------------------------- ### Empty Canvas Initialization Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/ui-tests/tests/notebooks/ipycanvas.ipynb Initializes an empty canvas with specified dimensions. This serves as a starting point for further drawing operations. ```python from ipycanvas import Canvas canvas = Canvas(width=200, height=200) ``` -------------------------------- ### Batch Drawing API Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/offscreen_canvas.ipynb Illustrates the batch API for drawing multiple shapes efficiently. This example sets up random colors and positions for `n` shapes but does not include the actual drawing commands. ```python # batch api shape = (1000,500) canvas = Canvas(width=shape[0], height=shape[1], layout=dict(width="100%")) await canvas.display() n = 100 # random colors rgb = np.random.randint(0, 255, size=(n, 3), dtype=np.uint8) # random positions x = np.random.randint(0, shape[0], size=n) y = np.random.randint(0, shape[1], size=n) ``` -------------------------------- ### Draw images on canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/ui-tests/tests/notebooks/ipycanvas.ipynb Demonstrates drawing images onto the canvas using `draw_image`. This example loads images from URLs and draws them onto one or more canvases. ```python from ipywidgets import Image from ipycanvas import Canvas, hold_canvas import urllib.request urllib.request.urlretrieve('https://github.com/jupyter-widgets-contrib/ipycanvas/raw/master/examples/sprites/smoke_texture0.png', 'smoke_texture0.png') urllib.request.urlretrieve('https://github.com/jupyter-widgets-contrib/ipycanvas/raw/master/examples/sprites/smoke_texture1.png', 'smoke_texture1.png') sprite1 = Image.from_file('smoke_texture0.png') sprite2 = Image.from_file('smoke_texture1.png') canvas = Canvas(width=300, height=300) canvas2 = Canvas(width=600, height=300) canvas.fill_style = '#a9cafc' canvas.fill_rect(0, 0, 300, 300) canvas.draw_image(sprite1, 50, 50) canvas.draw_image(sprite2, 100, 100) canvas2.draw_image(canvas, 0, 0) canvas2.draw_image(canvas, 300, 0) canvas2 ``` -------------------------------- ### Put image data (RGBA) on canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/ui-tests/tests/notebooks/ipycanvas.ipynb Similar to the RGB example, this uses `put_image_data` but includes an alpha channel to create an RGBA image. The alpha channel is derived from the blue channel in this case. ```python import numpy as np from ipycanvas import Canvas x = np.linspace(-1, 1, 600) y = np.linspace(-1, 1, 600) x_grid, y_grid = np.meshgrid(x, y) blue_channel = np.array(np.sin(x_grid**2 + y_grid) * 255, dtype=np.int32) red_channel = np.zeros_like(blue_channel) + 200 green_channel = np.zeros_like(blue_channel) + 50 alpha_channel = blue_channel image_data = np.stack((red_channel, blue_channel, green_channel, alpha_channel), axis=2) canvas = Canvas(width=image_data.shape[0], height=image_data.shape[1]) canvas.put_image_data(image_data, 0, 0) canvas ``` -------------------------------- ### Create Linear Gradients Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/styles_and_colors.md Creates a linear gradient using start and end coordinates and a list of color stops. ```python from ipycanvas import Canvas canvas = Canvas(width=700, height=50) gradient = canvas.create_linear_gradient( 0, 0, # Start position (x0, y0) 700, 0, # End position (x1, y1) # List of color stops [ (0, "red"), (1 / 6, "orange"), (2 / 6, "yellow"), (3 / 6, "green"), (4 / 6, "blue"), (5 / 6, "#4B0082"), (1, "violet"), ], ) canvas.fill_style = gradient canvas.fill_rect(0, 0, 700, 50) canvas ``` -------------------------------- ### Implement Particle Animation with Threading Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/Interaction during animation.ipynb Sets up a canvas with interactive particles, using a background thread to update positions and handle UI controls like start, stop, and reset. ```python # Setting up the canvas canvas2 = Canvas(width=500, height=500) # Some particles (as before) n_particles = 4100 x = np.array(np.random.rayleigh(250, n_particles)) y = np.array(np.random.rayleigh(250, n_particles)) size = np.random.randint(1, 3, n_particles) def handle_mouse_down(xpos, ypos): global x, y x_new = np.array(np.random.rayleigh(30, 100)) + xpos - 15 y_new = np.array(np.random.rayleigh(30, 100)) + ypos - 15 x = np.concatenate([x[-4000:], x_new]) y = np.concatenate([y[-4000:], y_new]) size = np.random.randint(1, 3, len(x)) draw_particles() # Register mouse click callback canvas2.on_mouse_down(handle_mouse_down) def draw_particles(): with hold_canvas(): canvas2.clear() # Clear the old animation step canvas2.fill_style = "green" canvas2.fill_rects(x, y, size) # Draw the new frame def update_particle_locations(): global x, y angles = perlin(x / 35, y / 35) * 3 x += np.sin(angles) * 0.3 y += np.cos(angles) * 0.3 stopped = Event() def loop(): while not stopped.wait(0.02): # the first call is in `interval` secs update_particle_locations() draw_particles() Thread(target=loop).start() # Start it by default start_btn = Button(description="Start") def start(btn): if stopped.isSet(): stopped.clear() Thread(target=loop).start() start_btn.on_click(start) stop_btn = Button(description="Stop") def stop(btn): if not stopped.isSet(): stopped.set() stop_btn.on_click(stop) reset_btn = Button(description="Randomize Particles") def reset(btn): global x, y, size x = np.array(np.random.rayleigh(250, n_particles)) y = np.array(np.random.rayleigh(250, n_particles)) size = np.random.randint(1, 3, n_particles) draw_particles() reset_btn.on_click(reset) display(canvas2, HBox([start_btn, stop_btn, reset_btn])) ``` -------------------------------- ### Control clock time with ipywidgets Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/clock.ipynb This code sets up interactive integer text widgets for hours and minutes, linked to the `draw_clock` function. It uses `datetime` to get the current time for initial values and `ipywidgets.observe` to update the clock whenever the text values change. Ensure `ipycanvas` and `ipywidgets` are installed. ```python import datetime import ipywidgets as widgets now = datetime.datetime.now() hour_text = widgets.IntText( value=now.hour, continuous_update=True, layout={"width": "50px"} ) minute_text = widgets.IntText( value=now.minute, continuous_update=True, layout={"width": "50px"} ) def on_text_change(change): draw_clock(int(hour_text.value), int(minute_text.value)) hour_text.observe(on_text_change, names="value") minute_text.observe(on_text_change, names="value") display(widgets.HBox([hour_text, widgets.Label(value=":"), minute_text])) on_text_change(0) ``` -------------------------------- ### Initializing animated particles Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/particle_system.ipynb Set up initial positions and velocities for animated particles. ```python x = np.array(np.random.rayleigh(250, n_particles), dtype=np.int32) y = np.array(np.random.rayleigh(250, n_particles), dtype=np.int32) size = np.random.randint(1, 3, n_particles) speed_x = np.random.randint(-40, 40, n_particles) speed_y = np.random.randint(-40, 40, n_particles) ``` -------------------------------- ### Initialize and animate the simulation Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/conways_game_of_life.ipynb Sets up the initial glider gun pattern and runs the simulation loop to update the canvas. ```python glider_gun =\ [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1], [1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] x = np.zeros((50, 70), dtype=bool) x[1:10,1:37] = glider_gun n_pixels = 15 canvas = RoughCanvas(width=x.shape[0]*n_pixels, height=x.shape[1]*n_pixels) canvas.fill_style = '#FFF0C9' canvas.stroke_style = 'white' canvas.fill_rect(0, 0, canvas.width, canvas.height) draw(x, canvas, '#5770B3') display(canvas) for _ in range(100): x = life_step(x) draw(x, canvas, '#5770B3') sleep(0.1) ``` -------------------------------- ### Create and use a pattern fill Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/ui-tests/tests/notebooks/ipycanvas.ipynb Demonstrates creating a pattern from an image URL using `create_pattern` and then using this pattern to fill a rectangle. ```python from ipycanvas import Canvas canvas = Canvas() pattern = canvas.create_pattern(Image.from_url("https://jupyter.org/assets/homepage/main-logo.svg")) canvas.fill_style = pattern canvas.fill_rect(0, 0, canvas.width, canvas.height) canvas ``` -------------------------------- ### Initialize particle data Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/Interaction during animation.ipynb Sets up initial particle positions and sizes using Rayleigh distribution. ```python # Create our particles n_particles = 4100 x = np.array(np.random.rayleigh(250, n_particles)) y = np.array(np.random.rayleigh(250, n_particles)) size = np.random.randint(1, 3, n_particles) ``` -------------------------------- ### Get Image Data with Callback Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/retrieve_images.md To get image data as a NumPy array within the same notebook cell, use `canvas.observe` to trigger `get_image_data` when the canvas is ready. This handles asynchronous drawing. ```python from ipycanvas import Canvas canvas = Canvas(width=200, height=200, sync_image_data=True) def get_array(*args, **kwargs): arr = canvas.get_image_data() # Do something with arr # Listen to changes on the ``image_data`` trait and call ``get_array`` when it changes. canvas.observe(get_array, "image_data") # Perform some drawings... ``` -------------------------------- ### Instantiate and display MonkeyCloud Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/3d_monkey.ipynb Creates an instance of the MonkeyCloud class and displays it. This will render the 3D point cloud in the output. ```python cloud = MonkeyCloud() cloud ``` -------------------------------- ### Apply Colors and Gradients Source: https://context7.com/jupyter-widgets-contrib/ipycanvas/llms.txt Demonstrates filling shapes with solid colors and linear gradients. ```python from ipycanvas import Canvas canvas = Canvas(width=500, height=200) # Solid color canvas.fill_style = "purple" canvas.fill_rect(10, 10, 100, 80) # Linear gradient linear_grad = canvas.create_linear_gradient( 130, 10, # Start point 280, 90, # End point [ # Color stops (0, "red"), (0.5, "yellow"), (1, "green") ] ) canvas.fill_style = linear_grad canvas.fill_rect(130, 10, 150, 80) ``` -------------------------------- ### Initialize Canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/Gradients.ipynb Import the Canvas class and initialize a new canvas instance. ```python from ipycanvas import Canvas ``` ```python canvas = Canvas(width=700, height=50) ``` ```python canvas2 = Canvas(width=570, height=200) ``` -------------------------------- ### Initialize canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/animation.ipynb Creates a canvas instance with specified dimensions. ```python size = 1000 canvas = Canvas(width=size, height=size) canvas ``` -------------------------------- ### Initialize and Display Map Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/mapping.ipynb Initializes a Map instance with specified dimensions, zoom level, and initial coordinates. The map is then displayed. ```python m = Map(788, 788, 7, 49, 2) m ``` -------------------------------- ### Creating and displaying a canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/particle_system.ipynb Instantiate a canvas object and display it in the notebook. ```python canvas = Canvas(width=800, height=500) canvas ``` ```python canvas = Canvas(width=800, height=500) canvas ``` -------------------------------- ### Get shape of the image data Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/binary_image.ipynb Displays the shape of the prepared image data array. This is useful for understanding the dimensions before drawing. ```python data.shape ``` -------------------------------- ### Import necessary libraries for ipycanvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/sprites.ipynb Import modules for image manipulation, numerical operations, and ipycanvas functionalities. These imports are required for most examples. ```python from random import choice, randint, uniform from math import pi from PIL import Image as PILImage import numpy as np from ipywidgets import Image from ipycanvas import Canvas, hold_canvas ``` -------------------------------- ### Initialize Canvas and Draw Background Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/drag_and_drop_example.ipynb Sets up the ipycanvas drawing surface and fills it with a background color. This is typically the first step in creating a visual application. ```python from ipycanvas import Canvas, hold_canvas canvas = Canvas(width=600, height=600) cavas.fill_style = "#584f4e" canvas.fill_rect(0, 0, 600, 600) ``` -------------------------------- ### Drawing Text with ipycanvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/drawing_text.md Demonstrates how to use the fill_text and stroke_text methods to draw text on a canvas. Includes examples of setting font properties. ```APIDOC ## Drawing Text ### Description Methods for drawing text on the canvas. ### Methods #### `fill_text(text, x, y, max_width=None)` Fills a given `text` at the given (`x`, `y`) position. Optionally with a maximum width to draw. #### `stroke_text(text, x, y, max_width=None)` Strokes a given `text` at the given (`x`, `y`) position. Optionally with a maximum width to draw. ### Styles and Colors Attributes to change text style: - `font` (str): The current text style being used when drawing text. Uses CSS font property syntax. Default: `"12px sans-serif"`. - `text_align` (str): Text alignment. Possible values: `"start"`, `"end"`, `"left"`, `"right"`, `"center"`. Default: `"start"`. - `text_baseline` (str): Baseline alignment. Possible values: `"top"`, `"hanging"`, `"middle"`, `"alphabetic"`, `"ideographic"`, `"bottom"`. Default: `"alphabetic"`. - `direction` (str): Directionality. Possible values: `"ltr"`, `"rtl"`, `"inherit"`. Default: `"inherit"`. **Note**: `fill_style`, `stroke_style`, `shadow_color`, etc. can also be used for coloring text and applying shadows. ``` -------------------------------- ### Create a Basic Canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/basic_usage.md Instantiate a Canvas widget with specified width and height in pixels. This canvas can be displayed directly in a Jupyter Notebook. ```python from ipycanvas import Canvas canvas = Canvas(width=200, height=200) canvas ``` -------------------------------- ### Get Tile Grid Calculation Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/mapping.ipynb Calculates the pixel and tile indices for a given viewport and number of tiles. Used for determining which map tiles to display. ```python def get_tile_grid(x, y, width, height, ntiles): def get_indices(x, width, ntiles): def _(x, width, p, ntiles, xs=None, ns=None): """p == 0: backward p == 1: forward Must be called with p=0 then p=1 """ x2 = (x % 1) * 256 if p == 0: xs = [width / 2 - x2] ns = [int(x)] else: x2 = 256 - x2 done = False while not done: if x2 >= width / 2: # out of canvas, don't show next tile done = True else: # show (part of) next tile x2 += 256 if p == 0: n1 = ns[-1] - 1 x1 = xs[-1] - 256 if n1 < 0: done = True else: ns.append(n1) xs.append(x1) else: n1 = ns[-1] + 1 x1 = xs[-1] + 256 if n1 >= ntiles: done = True else: ns.append(n1) xs.append(x1) if p == 0: xs = xs[::-1] ns = ns[::-1] return xs, ns xs, ns = _(x, width, 0, ntiles) xs, ns = _(x, width, 1, ntiles, xs, ns) return xs, ns xs, xn = get_indices(x, width, ntiles) ys, yn = get_indices(y, height, ntiles) def get_grid(xs, ys): xys = [] for j in ys: xys.append([]) for i in xs: xys[-1].append((i, j)) return xys xys = get_grid(xs, ys) xyn = get_grid(xn, yn) return {"pix": xys, "tile": xyn} ``` -------------------------------- ### Perform Drawings on Client Ready with ipycanvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/advanced.md Use the `on_client_ready` method to ensure drawings are performed after the client is ready to receive them, which is crucial for stateless widgets like ipycanvas when used with VoilĂ . ```python from ipycanvas import Canvas canvas = Canvas(width=100, height=50) def perform_drawings(): canvas.font = "32px serif" canvas.fill_text("VoilĂ !", 10, 32) canvas.on_client_ready(perform_drawings) canvas ``` -------------------------------- ### Drawing Styled Arcs with Varying Angles Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/ui-tests/tests/notebooks/ipycanvas.ipynb Generates random start and end angles for drawing multiple styled arcs. Requires numpy and math. ```python import numpy as np from ipycanvas import Canvas, hold_canvas import math canvas = Canvas(width=300, height=300) n_circles = 100 x = np.random.randint(0, canvas.width, size=(n_circles)) y = np.random.randint(0, canvas.width, size=(n_circles)) r = np.random.randint(10, 20, size=(n_circles)) start_angle = np.random.randint(0, 360, size=(n_circles)) end_angle = np.random.randint(0, 360, size=(n_circles)) start_angle = 0 end_angle = math.pi start_angle = np.random.random(n_circles) * math.pi ``` -------------------------------- ### Initialize a Canvas widget Source: https://context7.com/jupyter-widgets-contrib/ipycanvas/llms.txt Create a basic drawing surface by specifying dimensions and applying fill or stroke styles. ```python from ipycanvas import Canvas # Create a canvas with specific dimensions canvas = Canvas(width=400, height=300) # Draw a simple filled rectangle canvas.fill_style = "blue" canvas.fill_rect(50, 50, 100, 80) # Draw a stroked rectangle canvas.stroke_style = "red" canvas.line_width = 3 canvas.stroke_rect(200, 50, 100, 80) # Display the canvas canvas ``` -------------------------------- ### Initialize canvas and pixel size Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/conways_game_of_life.ipynb Sets the size of each pixel in the canvas and creates a `RoughCanvas` instance with dimensions based on the game grid and pixel size. ```python n_pixels = 15 canvas = RoughCanvas(width=x.shape[1] * n_pixels, height=x.shape[0] * n_pixels) ``` -------------------------------- ### Get Canvas Image Data as NumPy Array Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/retrieve_images.md Retrieve the canvas image data as a NumPy array using `get_image_data`. Set `sync_image_data` to `True` beforehand. ```python from ipycanvas import Canvas canvas = Canvas(width=200, height=200, sync_image_data=True) # Perform some drawings... arr1 = canvas.get_image_data() # Get the entire Canvas as a NumPy array arr2 = canvas.get_image_data( 50, 10, 40, 60 ) # Get the subpart defined by the rectangle at position (x=50, y=10) and of size (width=40, height=60) ``` -------------------------------- ### Configure Line Styles and Dashes Source: https://context7.com/jupyter-widgets-contrib/ipycanvas/llms.txt Sets line width, cap, and join styles. Also configures dash patterns for stroked lines. ```python from ipycanvas import Canvas canvas = Canvas(width=400, height=300) # Line width variations canvas.stroke_style = "blue" for i, width in enumerate([1, 3, 5, 10]): canvas.line_width = width canvas.begin_path() canvas.move_to(20, 30 + i * 40) canvas.line_to(150, 30 + i * 40) canvas.stroke() # Line cap styles caps = ["butt", "round", "square"] canvas.line_width = 15 for i, cap in enumerate(caps): canvas.line_cap = cap canvas.begin_path() canvas.move_to(200, 40 + i * 50) canvas.line_to(300, 40 + i * 50) canvas.stroke() # Dashed lines canvas.line_width = 2 canvas.line_cap = "butt" dashes = [[5, 5], [10, 5], [5, 10, 15, 10]] for i, dash in enumerate(dashes): canvas.set_line_dash(dash) canvas.begin_path() canvas.move_to(320, 30 + i * 40) canvas.line_to(390, 30 + i * 40) canvas.stroke() ``` -------------------------------- ### Register Client Ready Callback for Voila Source: https://context7.com/jupyter-widgets-contrib/ipycanvas/llms.txt Ensures drawing commands execute only after the canvas is fully initialized, which is critical for Voila dashboard rendering. ```python from ipycanvas import Canvas canvas = Canvas(width=300, height=200) def draw_on_ready(): """This callback runs when the canvas is ready to receive commands.""" canvas.fill_style = "green" canvas.fill_rect(20, 20, 260, 160) canvas.font = "24px Arial" canvas.fill_style = "white" canvas.text_align = "center" canvas.fill_text("Ready!", 150, 110) # Register the callback canvas.on_client_ready(draw_on_ready) canvas ``` -------------------------------- ### Initialize data structures Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/3d_monkey.ipynb Initializes empty lists to store vertices, vertex normals, and faces from the .obj file. ```python vertices = [] vertex_normals = [] faces = [] faces_normals = [] ``` -------------------------------- ### Create and Fill with Linear Gradient Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/ui-tests/tests/notebooks/ipycanvas.ipynb Creates a linear gradient with multiple color stops and fills a rectangle with it. The gradient is defined by start and end points and a list of color stops. Requires importing `Canvas` from `ipycanvas`. ```python from ipycanvas import Canvas canvas = Canvas(width=700, height=50) gradient = canvas.create_linear_gradient( 0, 0, # Start position (x0, y0) 700, 0, # End position (x1, y1) # List of color stops [ (0, 'red'), (1 / 6, 'orange'), (2 / 6, 'yellow'), (3 / 6, 'green'), (4 / 6, 'blue'), (5 / 6, '#4B0082'), (1, 'violet') ] ) cavas.fill_style = gradient cavas.fill_rect(0, 0, 700, 50) ``` -------------------------------- ### Draw thousands of transformed sprites efficiently Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/sprites.ipynb Utilize `hold_canvas` for batch drawing operations. This example demonstrates drawing 2,000 sprites with random positions, rotations, and scales, using pre-cached Canvas sprites for maximum performance. ```python canvas3 = Canvas(width=800, height=600) sprites = [canvas_sprite1, canvas_sprite2, canvas_sprite3] with hold_canvas(): for _ in range(2_000): canvas3.save() # Choose a random sprite texture sprite = sprites[choice(range(3))] # Choose a random sprite position pos_x = randint(0, canvas3.width - 50) pos_y = randint(0, canvas3.height - 50) # Choose a random rotation angle (but first set the rotation center with `translate`) canvas3.translate(pos_x, pos_y) canvas3.rotate(uniform(0.0, pi)) # Choose a random sprite size scale = uniform(0.2, 1.0) canvas3.scale(scale) # Restore the canvas center canvas3.translate(-pos_x, -pos_y) # Draw the sprite canvas3.draw_image(sprite, pos_x, pos_y) canvas3.restore() canvas3 ``` -------------------------------- ### Initializing particle data Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/particle_system.ipynb Generating random particle coordinates and sizes using NumPy. ```python n_particles = 100_000 x = np.array(np.random.rayleigh(250, n_particles), dtype=np.int32) y = np.array(np.random.rayleigh(250, n_particles), dtype=np.int32) size = np.random.randint(1, 3, n_particles) ``` -------------------------------- ### Draw Tree Function Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/fractals_tree.ipynb Orchestrates the drawing of a fractal tree. It clears the canvas, sets the starting translation and stroke style, and then calls the recursive leaf drawing function with random parameters for branching. The `hold_canvas` context manager is used for efficient drawing. ```python def draw_tree(canvas): with hold_canvas(): canvas.save() canvas.clear() canvas.translate(canvas.width / 2.0, canvas.height) canvas.stroke_style = "black" r_factor = uniform(0.6, 0.8) l_factor = uniform(0.6, 0.8) r_angle = uniform(pi / 10.0, pi / 5.0) l_angle = uniform(-pi / 5.0, -pi / 10.0) recursive_draw_leaf(canvas, 150, r_angle, r_factor, l_angle, l_factor) canvas.restore() ``` -------------------------------- ### Draw basic rectangles Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/drawing_shapes.md Demonstrates creating a canvas and using fill_rect, clear_rect, and stroke_rect methods. ```python from ipycanvas import Canvas canvas = Canvas(width=200, height=200) canvas.fill_rect(25, 25, 100, 100) canvas.clear_rect(45, 45, 60, 60) canvas.stroke_rect(50, 50, 50, 50) canvas ``` -------------------------------- ### Create Interactive Clock Controls with ipywidgets Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/clock.ipynb This code creates interactive integer text widgets for hours and minutes, linked to a clock drawing function. It uses ipywidgets and datetime. The `on_text_change` function redraws the clock whenever the hour or minute input changes. Ensure ipywidgets is installed. ```python import datetime import ipywidgets as widgets now = datetime.datetime.now() hour_text = widgets.IntText( value=now.hour, continuous_update=True, layout={"width": "50px"} ) minute_text = widgets.IntText( value=now.minute, continuous_update=True, layout={"width": "50px"} ) def on_text_change(change): draw_clock(int(hour_text.value), int(minute_text.value)) hour_text.observe(on_text_change, names="value") minute_text.observe(on_text_change, names="value") on_text_change(0) widgets.HBox([hour_text, widgets.Label(value=":"), minute_text]) ``` -------------------------------- ### Draw Lines Source: https://context7.com/jupyter-widgets-contrib/ipycanvas/llms.txt Initialize a canvas for drawing lines and paths. ```python import numpy as np from ipycanvas import Canvas canvas = Canvas(width=400, height=300) ``` -------------------------------- ### Instantiate Plot3d Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/plot3d.ipynb Create and display the 3D plot widget. ```python p = Plot3d() p ``` -------------------------------- ### Create a Rough Pie Chart Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/RoughCanvas.ipynb Construct a pie chart using `fill_arc` with different fill styles for each segment. Ensure the `math.pi` constant is imported for angle calculations. ```python from math import pi c = RoughCanvas(width=600, height=600) c.fill_style = "green" c.fill_arc(300, 300, 200, 0, 0.9 * pi) c.fill_style = "red" c.fill_arc(300, 300, 200, 0.9 * pi, pi + 0.2 * pi) c.fill_style = "blue" c.fill_arc(300, 300, 200, pi + 0.2 * pi, 2 * pi) c.stroke_style = "black" c.stroke_arc(300, 300, 200, 0, 2 * pi) c ``` -------------------------------- ### Display initial frame Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/Interaction during animation.ipynb Renders the first frame and displays the canvas widget. ```python draw_particles() # Running once to draw the first frame display(canvas) ``` -------------------------------- ### Draw shapes using path commands Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/drawing_paths.md Construct paths manually by calling begin_path followed by drawing commands, then rendering with stroke or fill. ```python from ipycanvas import Canvas canvas = Canvas(width=100, height=100) # Draw simple triangle shape canvas.begin_path() canvas.move_to(75, 50) canvas.line_to(100, 75) canvas.line_to(100, 25) canvas.fill() canvas ``` -------------------------------- ### Drawing Arcs and Circles Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/ui-tests/tests/notebooks/ipycanvas.ipynb Demonstrates drawing a filled arc and a stroked circle with different styles. Requires importing pi from math. ```python from math import pi from ipycanvas import Canvas canvas = Canvas(width=200, height=200) canvas.fill_style = 'red' canvas.stroke_style = 'blue' canvas.fill_arc(60, 60, 50, 0, pi) canvas.stroke_circle(60, 60, 40) canvas ``` -------------------------------- ### Initialize MultiCanvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/MultiCanvas.ipynb Create a MultiCanvas instance with a specified number of layers and dimensions. ```python m = MultiCanvas(n_canvases=3, width=200, height=200) ``` -------------------------------- ### Apply Multiple Filters to Text Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/styles_and_colors.md Demonstrates applying multiple filters like blur, contrast, and drop-shadow to text. Note that applying filters can be slow, especially with many shapes. ```python from ipycanvas import Canvas canvas = Canvas(width=400, height=300) canvas.fill_style = "green" canvas.filter = "blur(1px) contrast(1.4) drop-shadow(-9px 9px 3px #e81)" canvas.font = "48px serif" canvas.fill_text("Hello world!", 20, 150) canvas ``` -------------------------------- ### Draw Lines and Polylines Source: https://context7.com/jupyter-widgets-contrib/ipycanvas/llms.txt Demonstrates basic line drawing and rendering of connected points using NumPy arrays. ```python canvas.stroke_style = "red" canvas.line_width = 2 canvas.stroke_line(10, 10, 200, 150) ``` ```python n = 30 x = np.linspace(20, 380, n) y = 150 + 50 * np.sin(x * 0.05) points = np.stack((x, y), axis=1) canvas.stroke_style = "blue" canvas.stroke_lines(points) canvas ``` -------------------------------- ### Translate and draw polygons Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/batch_drawing.ipynb Demonstrates translating polygons using numpy linspace and rendering them with stroke_styled_polygons. ```python polygons += np.linspace(1.0, 100.0, num=n_polygons)[:, None, None] points_per_polygon = np.ones([n_polygons]) * n_points_per_polygon with hold_canvas(): canvas.stroke_styled_polygons(polygons, color=colors_fill) canvas ``` -------------------------------- ### Load image for pattern Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/Patterns.ipynb Load an image file to be used as a pattern source. ```python Image.from_file("pattern.png") ``` -------------------------------- ### Set Canvas Colors Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/styles_and_colors.md Demonstrates setting stroke and fill styles using valid HTML color strings. ```python from ipycanvas import Canvas canvas = Canvas(width=200, height=200) canvas.fill_style = "red" canvas.stroke_style = "blue" canvas.fill_rect(25, 25, 100, 100) canvas.clear_rect(45, 45, 60, 60) canvas.stroke_rect(50, 50, 50, 50) canvas ``` -------------------------------- ### Create canvas instance Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/Interaction during animation.ipynb Instantiates the canvas object with specified dimensions. ```python # Create the canvas canvas = Canvas(width=500, height=200) ``` -------------------------------- ### Batch API for Rectangles with Styled Colors Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/offscreen_canvas.ipynb Demonstrates drawing multiple rectangles with random positions, sizes, and solid fill colors using the batch API. Requires numpy for random data generation. ```python # batch api rects shape = (1000,500) canvas = Canvas(width=shape[0], height=shape[1], layout=dict(width="100%")) await canvas.display() n = 100 # random colors rgb = np.random.randint(0, 255, size=(n, 3), dtype=np.uint8) # random positions x = np.random.randint(0, shape[0], size=n) y = np.random.randint(0, shape[1], size=n) # random width and height w = np.random.randint(5, 50, size=n) h = np.random.randint(5, 50, size=n) cavas.fill_style = 'white' cavas.fill_styled_rects(x=x, y=y, width=w, height=h, color=rgb) ``` -------------------------------- ### Instantiate and Display Monkey Model Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/3d_monkey.ipynb Creates an instance of the Monkey class and displays it. This is the final step to render the 3D model in the Jupyter output. ```python monkey = Monkey() monkey ``` -------------------------------- ### Drawing Polygons with Varying Styles Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/ui-tests/tests/notebooks/ipycanvas.ipynb Shows how to draw multiple polygons with different fill colors and alpha values, and then draw outlines on top. Requires numpy and hold_canvas. ```python import numpy as np from ipycanvas import Canvas, hold_canvas canvas = Canvas(width=400, height=400) n_polygons = 20 points_per_polygon = np.random.randint(3, 6, size=n_polygons) total_points = np.sum(points_per_polygon) polygons = np.random.randint(0, 400, size=[total_points, 2]) alpha = np.random.random(n_polygons) colors_fill = np.random.randint(0, 255, size=(n_polygons, 3)) colors_outline = np.random.randint(0, 255, size=(n_polygons, 3)) with hold_canvas(): # the filling canvas.fill_styled_polygons( polygons, points_per_polygon=points_per_polygon, color=colors_fill, alpha=alpha ) # draw outlines ontop where each line has the same style canvas.stroke_style = "black" canvas.line_width = 2 canvas.stroke_polygons(polygons, points_per_polygon=points_per_polygon) canvas ``` -------------------------------- ### Optimize Drawings with hold_canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/basic_usage.md Use the `hold_canvas` context manager to batch drawing commands, sending them in a single update to improve performance. This is recommended over sending commands individually. ```python from ipycanvas import Canvas, hold_canvas canvas = Canvas(width=200, height=200) with hold_canvas(): # Perform drawings... pass ``` -------------------------------- ### Batch drawing polygons Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/examples/batch_drawing.ipynb Initializes and prepares polygon data for batch rendering. ```python canvas = Canvas(width=800, height=300) n_polygons = 50 # each polygon has 4 points n_points_per_polygon = 4 polygons = np.zeros([n_polygons, n_points_per_polygon, 2]) polygons[:, 0, 0] = 0.0 polygons[:, 0, 1] = 0.0 polygons[:, 1, 0] = 1.0 polygons[:, 1, 1] = 0.0 polygons[:, 2, 0] = 1.0 polygons[:, 2, 1] = 1.0 polygons[:, 3, 0] = 0.0 polygons[:, 3, 1] = 1.0 colors_fill = np.random.randint(0, 255, size=(n_polygons, 3)) colors_outline = np.random.randint(0, 255, size=(n_polygons, 3)) # scale each polygon polygons *= np.linspace(1.0, 200.0, num=n_polygons)[:, None, None] ``` -------------------------------- ### Create and use canvas patterns Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/offscreen_canvas.ipynb Define a pattern source and apply it to a canvas fill style. ```python from math import pi from ipycanvas.compat import Canvas pattern_source = Canvas(width=50, height=50) await pattern_source.display() pattern_source.fill_style = "#fec" pattern_source.fill_rect(0, 0, 50, 50) pattern_source.stroke_arc(0, 0, 50, 0, 0.5 * pi) ``` ```python canvas = Canvas(width=200, height=200) await canvas.display() pattern = canvas.create_pattern(pattern_source) canvas.fill_style = pattern canvas.fill_rect(0, 0, canvas.width, canvas.height) ``` -------------------------------- ### Initialize a RoughCanvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/rough_canvas.md Instantiate a RoughCanvas object with specified dimensions. ```python from ipycanvas import RoughCanvas canvas = RoughCanvas(width=200, height=200) canvas ``` -------------------------------- ### Create an animated canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/offscreen_canvas.ipynb Implement a render loop to animate shapes and gradients on a canvas. ```python canvas = Canvas(width=1600, height=1200, layout=dict(width="75%")) await canvas.display() class Animate(): def __init__(self, canvas): self.canvas = canvas self.canvas.font = '30px Arial' self.canvas.text_align = 'center' self.canvas.text_baseline = 'middle' # linear gradient color_stops = [ (0, 'red'), (0.2, 'orange'), (0.4, 'yellow'), (0.6, 'green'), (0.8, 'blue'), (1, 'purple') ] self.background_gradient = self.canvas.create_linear_gradient(0, 0, 0, canvas.height, color_stops=color_stops) # face gradient color_stops = [ (0, '#fca503'), (1, '#fcdb03') ] self.face_gradient = self.canvas.create_radial_gradient( canvas.width / 2.0, canvas.height / 2.0, 0, canvas.width / 2.0, canvas.height / 2.0, 500, color_stops=color_stops ) self.iter = 0 self.t0 = None self.rot = 0 def __call__(self, dt): canvas = self.canvas # draw gradient background canvas.save() canvas.fill_style = self.background_gradient canvas.fill_rect(0, 0, canvas.width, canvas.height) canvas.restore() self.iter += 1 canvas.save() canvas.translate(canvas.width/2, canvas.height/2) canvas.rotate(self.rot) self.rot += dt canvas.translate(-canvas.width/2, -canvas.height/2) canvas.fill_style = self.face_gradient canvas.fill_circle(canvas.width / 2.0, canvas.height / 2.0, 500) canvas.stroke_style = "black" canvas.line_width = 30 canvas.stroke_circle(canvas.width / 2.0, canvas.height / 2.0, 500) # left eye canvas.fill_style = "black" canvas.fill_circle(canvas.width / 2.7, canvas.height / 3.0, 100) # Right eye canvas.stroke_arc(canvas.width / 2.0, canvas.height / 2.0, 400, 0, pi, False) # Mouth canvas.stroke_arc(canvas.width - canvas.width / 2.7, canvas.height / 2.7, 100, 0, pi, True) canvas.restore() if self.iter == 1: self.t0 = time.time() else: t = time.time() av_dt = (t - self.t0)/ self.iter av_fps = 1.0/av_dt canvas.fill_text( f"Average FPS: {av_fps:.2f}", canvas.width / 2.0, canvas.height/ 2.0, ) set_render_loop(canvas, Animate(canvas)) ``` -------------------------------- ### Initialize ipycanvas Canvas Source: https://github.com/jupyter-widgets-contrib/ipycanvas/blob/master/docs/fractals_tree.ipynb Creates a new Canvas instance with specified dimensions. This canvas will be used for drawing. ```python canvas = Canvas(width=800, height=600) ```