API Reference#

Note that because we are exposing the Web Canvas API, you can find more tutorials and documentation following this link: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API

There are some API differences though:

  • The Canvas widget is directly exposing the CanvasRenderingContext2D API

  • All the API is written in snake_case instead of camelCase, so for example canvas.fillStyle = 'red' in JavaScript becomes canvas.fill_style = 'red' in Python

  • The Canvas widget exposes a clear method, canvas.clear() is a shortcut for canvas.clear_rect(0, 0, canvas.width, canvas.height)

  • We provide a hold_canvas context manager if you want to perform lots of commands at once

  • The Web canvas putImageData method does not support transparency and the current transformation state, our Canvas.put_image_data does support them!

class ipycanvas.canvas.Path2D(**kwargs: Any)#

Create a Path2D.

Parameters

value (str) – The path value, e.g. “M10 10 h 80 v 80 h -80 Z”

class ipycanvas.canvas.Pattern(**kwargs: Any)#

Create a Pattern.

Parameters
  • image (Canvas or MultiCanvas or ipywidgets.Image) – The source to be used as the pattern’s image

  • repetition (str) – A string indicating how to repeat the pattern’s image, can be “repeat” (both directions), “repeat-x” (horizontal only), “repeat-y” (vertical only), “no-repeat” (neither direction)

class ipycanvas.canvas.LinearGradient(**kwargs: Any)#

Create a LinearGradient.

class ipycanvas.canvas.RadialGradient(**kwargs: Any)#

Create a RadialGradient.

class ipycanvas.canvas.Canvas(**kwargs: Any)#

Create a Canvas widget.

Parameters
  • width (int) – The width (in pixels) of the canvas

  • height (int) – The height (in pixels) of the canvas

fill_style#

(valid HTML color or Gradient or Pattern) The color for filling rectangles and paths. Default to 'black'.

stroke_style#

(valid HTML color or Gradient or Pattern) The color for rectangles and paths stroke. Default to 'black'.

global_alpha#

(float) Transparency level. Default to 1.0.

font#

(str) Font for the text rendering. Default to '12px serif'.

text_align#

(str) Text alignment, possible values are 'start', 'end', 'left', 'right', and 'center'. Default to 'start'.

text_baseline#

(str) Text baseline, possible values are 'top', 'hanging', 'middle', 'alphabetic', 'ideographic' and 'bottom'. Default to 'alphabetic'.

direction#

(str) Text direction, possible values are 'ltr', 'rtl', and 'inherit'. Default to 'inherit'.

global_composite_operation#

(str) Global composite operation, possible values are listed below: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing#globalCompositeOperation

shadow_offset_x#

(float) Indicates the horizontal distance the shadow should extend from the object. This value isn’t affected by the transformation matrix. The default is 0.

shadow_offset_y#

(float) Indicates the vertical distance the shadow should extend from the object. This value isn’t affected by the transformation matrix. The default is 0.

shadow_blur#

(float) Indicates the size of the blurring effect; this value doesn’t correspond to a number of pixels and is not affected by the current transformation matrix. The default value is 0.

shadow_color#

(valid HTML color) A standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.

line_width#

(float) Sets the width of lines drawn in the future, must be a positive number. Default to 1.0.

line_cap#

(str) Sets the appearance of the ends of lines, possible values are 'butt', 'round' and 'square'. Default to 'butt'.

line_join#

(str) Sets the appearance of the “corners” where lines meet, possible values are 'round', 'bevel' and 'miter'. Default to 'miter'

miter_limit#

(float) Establishes a limit on the miter when two lines join at a sharp angle, to let you control how thick the junction becomes. Default to 10..

filter#

(str) Filter effects such as blurring and grayscaling. It is similar to the CSS filter property and accepts the same values. This property has no effect on Safari, see https://bugs.webkit.org/show_bug.cgi?id=198416

line_dash_offset#

(float) Specifies where to start a dash array on a line. Default is 0..

sleep(time)#

Make the Canvas sleep for time milliseconds.

create_linear_gradient(x0, y0, x1, y1, color_stops)#

Create a LinearGradient object given the start point, end point, and color stops.

Parameters
  • x0 (float) – The x-axis coordinate of the start point.

  • y0 (float) – The y-axis coordinate of the start point.

  • x1 (float) – The x-axis coordinate of the end point.

  • y1 (float) – The y-axis coordinate of the end point.

  • color_stops (list) – The list of color stop tuples (offset, color) defining the gradient.

create_radial_gradient(x0, y0, r0, x1, y1, r1, color_stops)#

Create a RadialGradient object given the start circle, end circle and color stops.

Parameters
  • x0 (float) – The x-axis coordinate of the start circle.

  • y0 (float) – The y-axis coordinate of the start circle.

  • r0 (float) – The radius of the start circle.

  • x1 (float) – The x-axis coordinate of the end circle.

  • y1 (float) – The y-axis coordinate of the end circle.

  • r1 (float) – The radius of the end circle.

  • color_stops (list) – The list of color stop tuples (offset, color) defining the gradient.

create_pattern(image, repetition='repeat')#

Create a Pattern.

Parameters
  • image (Canvas or MultiCanvas or ipywidgets.Image) – The source to be used as the pattern’s image

  • repetition (str) – A string indicating how to repeat the pattern’s image, can be “repeat” (both directions), “repeat-x” (horizontal only), “repeat-y” (vertical only), “no-repeat” (neither direction)

fill_rect(x, y, width, height=None)#

Draw a filled rectangle of size (width, height) at the (x, y) position.

stroke_rect(x, y, width, height=None)#

Draw a rectangular outline of size (width, height) at the (x, y) position.

fill_rects(x, y, width, height=None)#

Draw filled rectangles of sizes (width, height) at the (x, y) positions.

Where x, y, width and height arguments are NumPy arrays, lists or scalar values. If height is None, it is set to the same value as width.

stroke_rects(x, y, width, height=None)#

Draw a rectangular outlines of sizes (width, height) at the (x, y) positions.

Where x, y, width and height arguments are NumPy arrays, lists or scalar values. If height is None, it is set to the same value as width.

fill_styled_rects(x, y, width, height, color, alpha=1)#

Draw filled and styled rectangles of sizes (width, height) at the (x, y) positions

Where x, y, width and height arguments are NumPy arrays, lists or scalar values. If height is None, it is set to the same value as width. color is an (n_rect x 3) NumPy array with the colors and alpha is an (n_rect) NumPy array with the alpha channel values.

stroke_styled_rects(x, y, width, height, color, alpha=1)#

Draw rectangular styled outlines of sizes (width, height) at the (x, y) positions.of sizes (width, height)

Where x, y, width and height arguments are NumPy arrays, lists or scalar values. If height is None, it is set to the same value as width. color is an (n_rect x 3) NumPy array with the colors and alpha is an (n_rect) NumPy array with the alpha channel values.

clear_rect(x, y, width, height=None)#

Clear the specified rectangular area of size (width, height) at the (x, y) position, making it fully transparent.

fill_arc(x, y, radius, start_angle, end_angle, anticlockwise=False)#

Draw a filled arc centered at (x, y) with a radius of radius from start_angle to end_angle.

fill_circle(x, y, radius)#

Draw a filled circle centered at (x, y) with a radius of radius.

stroke_arc(x, y, radius, start_angle, end_angle, anticlockwise=False)#

Draw an arc outline centered at (x, y) with a radius of radius.

stroke_circle(x, y, radius)#

Draw a circle centered at (x, y) with a radius of radius.

fill_arcs(x, y, radius, start_angle, end_angle, anticlockwise=False)#

Draw filled arcs centered at (x, y) with a radius of radius.

Where x, y, radius and other arguments are NumPy arrays, lists or scalar values.

stroke_arcs(x, y, radius, start_angle, end_angle, anticlockwise=False)#

Draw an arc outlines centered at (x, y) with a radius of radius.

Where x, y, radius and other arguments are NumPy arrays, lists or scalar values.

fill_circles(x, y, radius)#

Draw filled circles centered at (x, y) with a radius of radius.

Where x, y, radius and other arguments are NumPy arrays, lists or scalar values.

stroke_circles(x, y, radius)#

Draw a circle outlines centered at (x, y) with a radius of radius.

Where x, y, radius and other arguments are NumPy arrays, lists or scalar values.

fill_styled_circles(x, y, radius, color, alpha=1)#

Draw a filled circles centered at (x, y) with a radius of radius.

Where x, y, radius and alpha`  are NumPy arrays, lists or scalar values. ``color must be an (nx3) NumPy arrays with the color for each circle.

stroke_styled_circles(x, y, radius, color, alpha=1)#

Draw filled circles centered at (x, y) with a radius of radius.

Where x, y, radius and alpha are NumPy arrays, lists or scalar values. color must be an nx3 NumPy arrays with the color for each circle

fill_styled_arcs(x, y, radius, start_angle, end_angle, color, alpha=1, anticlockwise=False)#

Draw filled and styled arcs centered at (x, y) with a radius of radius.

Where x, y, radius and other arguments are NumPy arrays, lists or scalar values.

stroke_styled_arcs(x, y, radius, start_angle, end_angle, color, alpha=1, anticlockwise=False)#

Draw an styled arc outlines centered at (x, y) with a radius of radius.

Where x, y, radius and other arguments are NumPy arrays, lists or scalar values.

fill_polygon(points)#

Fill a polygon from a list of points [(x1, y1), (x2, y2), ..., (xn, yn)].

stroke_polygon(points)#

Draw polygon outline from a list of points [(x1, y1), (x2, y2), ..., (xn, yn)].

fill_polygons(points, points_per_polygon=None)#

” Draw many filled polygons at once:

Parameters
  • points (list or ndarray) –

    The polygons points:

    The points can be specified as list or as ndarray: If the points are a list it must a an be a list of ndarrays, where each ndarray is a nx2 array of coordinates (n can be different for each entry) If the points are given as ndarray it must be either:

    • a 3d array: the shape of the array is (n_polyons, n_points_per_polygon, 2)

    • a 2d array: the shape of the array is (n, 2) and in additional points_per_polygon must be specified st. we know the the number of points for each individual polygon. Note that the number of points in points must match the points_per_polygon. array: ie: np.sum(points_per_polygon) == points.shape[0]

  • points_per_polygon (ndarray) – ndarray with number of points for each polygon. Must only be given if points are given as flat 2D array.

stroke_polygons(points, points_per_polygon=None)#

” Draw many stroked polygons at once:

Parameters
  • points (list or ndarray) –

    The polygons points:

    The points can be specified as list or as ndarray: If the points are a list it must a an be a list of ndarrays, where each ndarray is a nx2 array of coordinates (n can be different for each entry) If the points are given as ndarray it must be either:

    • a 3d array: the shape of the array is (n_polyons, n_points_per_polygon, 2)

    • a 2d array: the shape of the array is (n, 2) and in additional points_per_polygon must be specified st. we know the the number of points for each individual polygon. Note that the number of points in points must match the points_per_polygon. array: ie: np.sum(points_per_polygon) == points.shape[0]

  • points_per_polygon (ndarray) – ndarray with number of points for each polygon. Must only be given if points are given as flat 2D array.

fill_styled_polygons(points, color, alpha=1, points_per_polygon=None)#

” Draw many filled polygons at once:

Parameters
  • points (list or ndarray) –

    The polygons points:

    The points can be specified as list or as ndarray: If the points are a list it must a an be a list of ndarrays, where each ndarray is a nx2 array of coordinates (n can be different for each entry) If the points are given as ndarray it must be either:

    • a 3d array: the shape of the array is (n_polyons, n_points_per_polygon, 2)

    • a 2d array: the shape of the array is (n, 2) and in additional points_per_polygon must be specified st. we know the the number of points for each individual polygon. Note that the number of points in points must match the points_per_polygon. array: ie: np.sum(points_per_polygon) == points.shape[0]

  • color (ndarray) – An (n_polyons,3) array with the color for each polygon

  • alpha (ndarray,list,scalar) – An array with the alpha value for each polygon. Can be a scalar and the same value is used for all polygons

  • points_per_polygon (ndarray) – ndarray with number of points for each polygon. Must only be given if points are given as flat 2D array.

stroke_styled_polygons(points, color, alpha=1, points_per_polygon=None)#

” Draw many stroked polygons at once:

Parameters
  • points (list or ndarray) –

    The polygons points:

    The points can be specified as list or as ndarray: If the points are a list it must a an be a list of ndarrays, where each ndarray is a nx2 array of coordinates (n can be different for each entry) If the points are given as ndarray it must be either:

    • a 3d array: the shape of the array is (n_polyons, n_points_per_polygon, 2)

    • a 2d array: the shape of the array is (n, 2) and in additional points_per_polygon must be specified st. we know the the number of points for each individual polygon. Note that the number of points in points must match the points_per_polygon. array: ie: np.sum(points_per_polygon) == points.shape[0]

  • color (ndarray) – An (n_polyons,3) array with the color for each polygon

  • alpha (ndarray,list,scalar) – An array with the alpha value for each polygon. Can be a scalar and the same value is used for all polygons

  • points_per_polygon (ndarray) – ndarray with number of points for each polygon. Must only be given if points are given as flat 2D array.

stroke_line(x1, y1, x2, y2)#

Draw a line from (x1, y1) to (x2, y2).

stroke_lines(points)#

Draw a path of consecutive lines from a list of points [(x1, y1), (x2, y2), ..., (xn, yn)].

stroke_styled_line_segments(points, color, alpha=1, points_per_line_segment=None)#

Draw many line segments at once:

Parameters
  • points (list or ndarray) –

    The line_segments points:

    The points can be specified as list or as ndarray: If the points are a list it must a an be a list of ndarrays, where each ndarray is a nx2 array of coordinates (n can be different for each entry) If the points are given as ndarray it must be either:

    • a 3d array: the shape of the array is (n_line_segments, n_points_per_polygon, 2)

    • a 2d array: the shape of the array is (n, 2) and in additional points_per_line_segment

      must be specified st. we know the the number of points for each individual line_segment. Note that the number of points in points must match the points_per_line_segment. array: ie: np.sum(points_per_line_segment) == points.shape[0]

  • color (ndarray) – An (n_line_segments,3) array with the color for each line_segment

  • alpha (ndarray,list,scalar) – An array with the alpha value for each line_segment. Can be a scalar and the same value is used for all line_segments

  • points_per_line_segment (ndarray) – ndarray with number of points for each line_segment. Must only be given if points are given as flat 2D array.

stroke_line_segments(points, points_per_line_segment=None)#

Draw many stroked line_segments at once:

Parameters
  • points (list or ndarray) –

    The line_segments points:

    The points can be specified as list or as ndarray: If the points are a list it must a an be a list of ndarrays, where each ndarray is a nx2 array of coordinates (n can be different for each entry) If the points are given as ndarray it must be either:

    • a 3d array: the shape of the array is (n_line_segments, n_points_per_polygon, 2)

    • a 2d array: the shape of the array is (n, 2) and in additional points_per_line_segment ` must be specified st. we know the the number of points for each individual polygon. Note that the number of points in ``points` must match the points_per_line_segment . array: ie: np.sum(points_per_line_segment ) == points.shape[0]

  • points_per_line_segment (ndarray) – ndarray with number of points for each polygon. Must only be given if points are given as flat 2D array.

begin_path()#

Call this method when you want to create a new path.

close_path()#

Add a straight line from the current point to the start of the current path.

If the shape has already been closed or has only one point, this function does nothing. This method doesn’t draw anything to the canvas directly. You can render the path using the stroke() or fill() methods.

stroke()#

Stroke (outlines) the current path with the current stroke_style.

fill(rule_or_path='nonzero')#

Fill the current path with the current fill_style and given the rule, or fill the given Path2D.

Possible rules are nonzero and evenodd.

move_to(x, y)#

Move the “pen” to the given (x, y) coordinates.

line_to(x, y)#

Add a straight line to the current path by connecting the path’s last point to the specified (x, y) coordinates.

Like other methods that modify the current path, this method does not directly render anything. To draw the path onto the canvas, you can use the fill() or stroke() methods.

rect(x, y, width, height)#

Add a rectangle of size (width, height) at the (x, y) position in the current path.

arc(x, y, radius, start_angle, end_angle, anticlockwise=False)#

Add a circular arc centered at (x, y) with a radius of radius to the current path.

The path starts at start_angle and ends at end_angle, and travels in the direction given by anticlockwise (defaulting to clockwise: False).

ellipse(x, y, radius_x, radius_y, rotation, start_angle, end_angle, anticlockwise=False)#

Add an ellipse centered at (x, y) with the radii radius_x and radius_y to the current path.

The path starts at start_angle and ends at end_angle, and travels in the direction given by anticlockwise (defaulting to clockwise: False).

arc_to(x1, y1, x2, y2, radius)#

Add a circular arc to the current path.

Using the given control points (x1, y1) and (x2, y2) and the radius.

quadratic_curve_to(cp1x, cp1y, x, y)#

Add a quadratic Bezier curve to the current path.

It requires two points: the first one is a control point and the second one is the end point. The starting point is the latest point in the current path, which can be changed using move_to() before creating the quadratic Bezier curve.

bezier_curve_to(cp1x, cp1y, cp2x, cp2y, x, y)#

Add a cubic Bezier curve to the current path.

It requires three points: the first two are control points and the third one is the end point. The starting point is the latest point in the current path, which can be changed using move_to() before creating the Bezier curve.

fill_text(text, x, y, max_width=None)#

Fill a given text at the given (x, y) position. Optionally with a maximum width to draw.

stroke_text(text, x, y, max_width=None)#

Stroke a given text at the given (x, y) position. Optionally with a maximum width to draw.

get_line_dash()#

Return the current line dash pattern array containing an even number of non-negative numbers.

set_line_dash(segments)#

Set the current line dash pattern.

draw_image(image, x=0, y=0, width=None, height=None)#

Draw an image on the Canvas at the coordinates (x, y) and scale it to (width, height).

put_image_data(image_data, x=0, y=0)#

Draw an image on the Canvas.

image_data should be a NumPy array containing the image to draw and x and y the pixel position where to draw. Unlike the CanvasRenderingContext2D.putImageData method, this method is affected by the canvas transformation matrix, and supports transparency.

create_image_data(width, height)#

Create a NumPy array of shape (width, height, 4) representing a table of pixel colors.

clip()#

Turn the path currently being built into the current clipping path.

You can use clip() instead of close_path() to close a path and turn it into a clipping path instead of stroking or filling the path.

save()#

Save the entire state of the canvas.

restore()#

Restore the most recently saved canvas state.

translate(x, y)#

Move the canvas and its origin on the grid.

x indicates the horizontal distance to move, and y indicates how far to move the grid vertically.

rotate(angle)#

Rotate the canvas clockwise around the current origin by the angle number of radians.

scale(x, y=None)#

Scale the canvas units by x horizontally and by y vertically. Both parameters are real numbers.

If y is not provided, it is defaulted to the same value as x. Values that are smaller than 1.0 reduce the unit size and values above 1.0 increase the unit size. Values of 1.0 leave the units the same size.

transform(a, b, c, d, e, f)#

Multiply the current transformation matrix with the matrix described by its arguments.

The transformation matrix is described by: [[a, c, e], [b, d, f], [0, 0, 1]].

set_transform(a, b, c, d, e, f)#

Reset the current transform to the identity matrix, and then invokes the transform() method with the same arguments.

This basically undoes the current transformation, then sets the specified transform, all in one step.

reset_transform()#

Reset the current transform to the identity matrix.

This is the same as calling: set_transform(1, 0, 0, 1, 0, 0).

clear()#

Clear the entire canvas. This is the same as calling clear_rect(0, 0, canvas.width, canvas.height).

flush()#

Flush all the cached commands and clear the cache.

on_client_ready(callback, remove=False)#

Register a callback that will be called when a new client is ready to receive draw commands.

When a new client connects to the kernel he will get an empty Canvas (because the canvas is almost stateless, the new client does not know what draw commands were previously sent). So this function is useful for replaying your drawing whenever a new client connects and is ready to receive draw commands.

on_mouse_move(callback, remove=False)#

Register a callback that will be called on mouse move.

on_mouse_down(callback, remove=False)#

Register a callback that will be called on mouse click down.

on_mouse_up(callback, remove=False)#

Register a callback that will be called on mouse click up.

on_mouse_out(callback, remove=False)#

Register a callback that will be called on mouse out of the canvas.

on_touch_start(callback, remove=False)#

Register a callback that will be called on touch start (new finger on the screen).

on_touch_end(callback, remove=False)#

Register a callback that will be called on touch end (a finger is not touching the screen anymore).

on_touch_move(callback, remove=False)#

Register a callback that will be called on touch move (finger moving on the screen).

on_touch_cancel(callback, remove=False)#

Register a callback that will be called on touch cancel.

on_key_down(callback, remove=False)#

Register a callback that will be called on keyboard event.

class ipycanvas.canvas.RoughCanvas(**kwargs: Any)#

Create a RoughCanvas widget. It gives a hand-drawn-like style to your drawings.

Parameters
  • width (int) – The width (in pixels) of the canvas

  • height (int) – The height (in pixels) of the canvas

rough_fill_style#

(str) Sets the appearance of the filling, possible values are 'hachure', 'solid', 'zigzag', 'cross-hatch', 'dots', 'sunburst', 'dashed', 'zigzag-line'. Default to 'hachure'.

roughness#

(float) Numerical value indicating how rough the drawing is. A rectangle with the roughness of 0 would be a perfect rectangle. There is no upper limit to this value, but a value over 10 is mostly useless. Default to '1'.

bowing#

(float) Numerical value indicating how curvy the lines are when drawing a sketch. A value of 0 will cause straight lines. Default to '1'.

class ipycanvas.canvas.MultiCanvas(**kwargs: Any)#

Create a MultiCanvas widget with n_canvases Canvas widgets.

Parameters
  • n_canvases (int) – The number of canvases to create

  • width (int) – The width (in pixels) of the canvases

  • height (int) – The height (in pixels) of the canvases

on_client_ready(callback, remove=False)#

Register a callback that will be called when a new client is ready to receive draw commands.

When a new client connects to the kernel he will get an empty Canvas (because the canvas is almost stateless, the new client does not know what draw commands were previously sent). So this function is useful for replaying your drawing whenever a new client connects and is ready to receive draw commands.

on_mouse_move(callback, remove=False)#

Register a callback that will be called on mouse move.

on_mouse_down(callback, remove=False)#

Register a callback that will be called on mouse click down.

on_mouse_up(callback, remove=False)#

Register a callback that will be called on mouse click up.

on_mouse_out(callback, remove=False)#

Register a callback that will be called on mouse out of the canvas.

on_touch_start(callback, remove=False)#

Register a callback that will be called on touch start (new finger on the screen).

on_touch_end(callback, remove=False)#

Register a callback that will be called on touch end (a finger is not touching the screen anymore).

on_touch_move(callback, remove=False)#

Register a callback that will be called on touch move (finger moving on the screen).

on_touch_cancel(callback, remove=False)#

Register a callback that will be called on touch cancel.

on_key_down(callback, remove=False)#

Register a callback that will be called on keyboard event.

clear()#

Clear the Canvas.

flush()#

Flush all the cached commands and clear the cache.

class ipycanvas.canvas.MultiRoughCanvas(**kwargs: Any)#

Create a MultiRoughCanvas widget with n_canvases RoughCanvas widgets.

Parameters
  • n_canvases (int) – The number of rough canvases to create

  • width (int) – The width (in pixels) of the canvases

  • height (int) – The height (in pixels) of the canvases

ipycanvas.canvas.hold_canvas(canvas=None)#

Hold any drawing, and perform all commands in a single shot at the end.

This is way more efficient than sending commands one by one.