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.size[0], canvas.size[1])

  • 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(value)

Create a Path2D.

Parameters

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

class ipycanvas.canvas.Canvas(*args, **kwargs)

Create a Canvas widget.

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

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

  • caching (boolean) – Whether commands should be cached or not

fill_style

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

stroke_style

(valid HTML color) 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

//developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing#globalCompositeOperation

Type

(str) Global composite operation, possible values are listed below

Type

https

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..

line_dash_offset

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

caching = None

Whether commands should be cached or not

sleep(time)

Make the Canvas sleep for time milliseconds.

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.

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.

stroke_line(x1, y1, x2, y2)

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

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.

class ipycanvas.canvas.RoughCanvas(*args, **kwargs)

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

  • caching (boolean) – Whether commands should be cached or not

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(n_canvases=3, *args, **kwargs)

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.

clear()

Clear the Canvas.

flush()

Flush all the cached commands and clear the cache.

class ipycanvas.canvas.MultiRoughCanvas(n_canvases=3, *args, **kwargs)

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)

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

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

Parameters

canvas (ipycanvas.canvas.Canvas) – The canvas widget on which to hold the commands