HtmlViewport

class visualife.core.HtmlViewport(div_element, svg_width, svg_height, id='visualife_drawing', **kwargs)

Bases: visualife.core.SvgViewport

Draws graphics on a WWW page, in a given <svg> element of a HTML page. :param div_element: (string) name of a DIV element where a SVG element will be inserted :param x_min: (float) minimum value for x coordinate of graphics :param y_min: (float) minimum value for y coordinate of graphics :param x_max: (float) maximum value for x coordinate of graphics :param y_max: (float) maximum value for y coordinate of graphics :param svg_width: (int) width of an SVG element in pixels; the x_max - x_min range will be

projected on svg_width pixels
Parameters:
  • svg_height – (int) height of an SVG element in pixels; the y_max - y_min range will be projected on svg_height pixels
  • id – (string) ID string will be used to identify the content of this viewport in an HTML page; it will be assigned to the respective SVG element
  • kwargs – see below; note that the **kwargs dictionary will be passed to the base class constructor
Keyword Arguments:
 
  • if_interactive (bool) – when set to True, this viewport will handle drag and zoom events; default is False. One can use True for inner viewports
  • download_button (bool) – when set to true, a “download” button will be drawn in the figure; this allows user to download the current state of graphics in this viewport in SVG format

Attributes Summary

default_drawing_style
default_text_style
id
innerHTML Returns SVG accumulated by this viewport.
is_inner_viewport Returns true if this viewport is embedded inside another SVG
parent_viewport Returns the parent of this viewport Returns None if this viewport is not an inner one
style Defines the default drawing style
svg Returns <svg> element of a WWW page
svg_height Height of the SVG element used by this viewport.
svg_width Width of the SVG element used by this viewport.
text_style Defines the default style for drawing text

Methods Summary

add_filter(id_str[, if_black]) Adds a filter to <defs> section of SVG
add_font(font_name, fmat_location)
apply_binding()
circle(id_str, x, y, r, **kwargs) Creates a <circle> element
circles_group(gid, x, y, c, r, **kwargs) Group of circles drawn in a single batch.
clear() Clears the viewport by removing all its children elements
close() Closes the SVG tag and sets styles for drawing and text
close_clip_path() Closes an open clipping path
close_group() Close an open group
close_marker() Closes an open marker definition
define_binding(id_str, on_what, func) Binds a function on given event to the element with given id
ellipse(id_str, x, y, rx, ry, **kwargs) Creates a <ellipse> element
error_msg(msg) Prints error message.
get_viewbox() Returns viewbox parameters
image(img_id, x, y, w, h, href, **kwargs) Draws a raster image in this SVG viewport :param img_id: (string) element id, assigned to this image :param x: (float) X :param y: (float) Y :param w: (float) width of the image :param h: (float) height of the image :param href: (string) file name with path :param kwargs: :return:
insert_viewport(vp, x0, y0) Inserts an SVG viewport into this SVG
line(id_str, xb, yb, xe, ye, **kwargs) Creates a <line> element
lines_group(gid, x, y, c, **kwargs) Group of lines drawn in a single batch.
path(id_str, elements, **kwargs) Draws a path
polygon(id_str, points, **kwargs)
polyline(id_str, *points, **kwargs) Creates a <polyline> element
radial_gradient(id_str, stop1, stop2, **kwargs) Adds radial gradient to an element with a given id
rect(id_str, x, y, w, h, **kwargs) Creates a <rect> element
rhomb(id_str, x, y, r, **kwargs) Draws a rhomb
rhomb_group(gid, x, y, c, r, **kwargs) Group of rhombs drawn in a single batch.
scale_x() Returns a factor used to transform drawing X coordinates to internal SVG coordinates (X axis)
scale_y() Returns a factor used to transform drawing Y coordinates to internal SVG coordinates (Y axis)
set_background(color) Sets the background color - will be applied in the next clear() method call
set_viewbox(x0, y0, w, h) Sets viewbox parameters
square(id_str, x, y, a, **kwargs) Creates a square as <rect> element
squares_grid(gid, x0, y0, w, h, rows, …) Draws a grid of rectangles.
squares_group(gid, x, y, c, a, **kwargs) Group of squares drawn in a single batch.
start_clip_path(id_str) Start a clipping path
start_group(id_str, **kwargs) Start a new group
start_marker(id_str, view_box, ref_x, ref_y, …) Start a marker definition
text(id_str, x, y, text, **kwargs) Adds text to the viewport
text_length(text, **kwargs) Measures the dimensions (in pixels) of a text as it would appear on a page
triangle(id_str, x, y, r, **kwargs) Draws a triangle
triangle_group(gid, x, y, c, r, **kwargs) Group of triangles drawn in a single batch.
viewport_name() Returns the name if this viewport, which is always “HTML”

Attributes Documentation

default_drawing_style = '\n stroke:black;\n '
default_text_style = 'stroke-width:0;\n font-size: 10px;\n font-family:sans-serif;\n font-weight:normal;\n text-anchor:middle;\n color: black;\n '
id
innerHTML

Returns SVG accumulated by this viewport.

The returned SVG contains header (i.e. <SVG> element), all defined gradients, markers etc. but there is no closing tag (i.e. no </SVG>)

is_inner_viewport

Returns true if this viewport is embedded inside another SVG

parent_viewport

Returns the parent of this viewport Returns None if this viewport is not an inner one

style

Defines the default drawing style

Getter:returns the style
Type:string
svg

Returns <svg> element of a WWW page

svg_height

Height of the SVG element used by this viewport.

Returns:SVG element height
svg_width

Width of the SVG element used by this viewport.

Returns:SVG element width
text_style

Defines the default style for drawing text

Getter:returns the text style
Type:string

Methods Documentation

add_filter(id_str, if_black=True)

Adds a filter to <defs> section of SVG

add_font(font_name: str, fmat_location)
apply_binding()
circle(id_str, x, y, r, **kwargs)

Creates a <circle> element

Parameters:
  • id_str – string to be used as the ID of the element
  • x – (number) x coordinate of the center
  • y – (number) y coordinate of the center
  • r – (number) radius of this circle
  • kwargs – parameters to prepare style attributes

See also

circles_group() method, which draws multiple circles in a single batch. In that example however all circles have the same stroke and transparency

from random import random
from browser import document
from visualife.core import HtmlViewport
from visualife.core.styles import rgb_to_hex

drawing = HtmlViewport(document['svg-circle'],600,150)
n_x, n_y = 20, 5
for i in range(n_x):
  for j in range(n_y):
      drawing.circle("c-%d-%d" % (i, j), i*30, j*30, random()*50, stroke="darker",
        fill=rgb_to_hex((255, i*255/n_x, j*255/n_y)), fill_opacity=random())
drawing.close()
circles_group(gid, x, y, c, r, **kwargs)

Group of circles drawn in a single batch.

This method has been devised to draw circles efficiently. All the circles will be placed in a single group. Graphics parameters from **kwargs fill be assigned to the group element. Therefore this method does not allow styling each circle separately except its radius and color.

Parameters:
  • gid – (string) id assigned to the whole group of circles
  • x – (list(float)) list of X coordinates
  • y – (list(float)) list of Y coordinates
  • c – (color or list(color)) list of colors for circles or a single color - the same for all circles
  • r – (float or list(float)) list of radii for circles or a single radii - the same for all circles
  • kwargs – other graphics parameters assigned to this group rather than separately to each circle

See also

circle() method, which draws circles separately and allows to style them; to the contrary of this example, in the circle() figure circles have different transparency and stroke

from random import random
from browser import document
from visualife.core import HtmlViewport
from visualife.core.styles import rgb_to_hex

drawing = HtmlViewport(document['svg-circles'],600,150)
x, y, c, r = [], [], [], []
n_x, n_y = 20, 5
for i in range(n_x):
    for j in range(n_y):
        x.append(i*30)
        y.append(j*30)
        c.append(rgb_to_hex((255, i*255/n_x, j*255/n_y)))
        r.append(random()*50)
drawing.circles_group("circles-grp", x, y, c, r)
drawing.close()
clear()

Clears the viewport by removing all its children elements

close()

Closes the SVG tag and sets styles for drawing and text

close_clip_path()

Closes an open clipping path

close_group()

Close an open group

close_marker()

Closes an open marker definition

define_binding(id_str, on_what, func)

Binds a function on given event to the element with given id

Parameters:
  • id_str – id of element you want to bind event to
  • on_what – HTML event as mouseover or click
  • func – function to bind
ellipse(id_str, x, y, rx, ry, **kwargs)

Creates a <ellipse> element

Parameters:
  • id_str – string to be used as the ID of the element
  • x – x coordinate of a center
  • y – y coordinate of a center
  • rx – x radius length
  • ry – y radius length
  • kwargs – parameters to prepare style attributes
error_msg(msg)

Prints error message.

This polymorphic method prints a given error message to browser’s console; SvgViewport will print to std.cerr;

get_viewbox()

Returns viewbox parameters

image(img_id, x, y, w, h, href, **kwargs)

Draws a raster image in this SVG viewport :param img_id: (string) element id, assigned to this image :param x: (float) X :param y: (float) Y :param w: (float) width of the image :param h: (float) height of the image :param href: (string) file name with path :param kwargs: :return:

insert_viewport(vp, x0, y0)

Inserts an SVG viewport into this SVG

The internal flag vp.__is_inner_viewport will be set to True by this call; vp.__parent_viewport will store the self reference

line(id_str, xb, yb, xe, ye, **kwargs)

Creates a <line> element

Parameters:
  • id_str – string to be used as the ID of the element
  • xb – x coordinate of line begin
  • yb – y coordinate of line begin
  • xe – side length of line end
  • ye – side length of line end
  • kwargs – parameters to prepare style attributes
lines_group(gid, x, y, c, **kwargs)

Group of lines drawn in a single batch.

This method has been devised to draw lines efficiently. All the lines will be placed in a single group. Graphics parameters from **kwargs fill be assigned to the group element. Therefore this method does not allow styling each square separately except its radius and color.

Parameters:
  • gid – (string) id assigned to the whole group of lines
  • x – (list(float)) list of X coordinates
  • y – (list(float)) list of Y coordinates
  • c – (color or list(color)) list of colors for lines or a single color - the same for all lines
  • kwargs – other graphics parameters assigned to this group rather than separately to each line
path(id_str, elements, **kwargs)

Draws a path

:param id_str:(string) - id string of a created element :param elements:(string or list) - list of elements or a raw path data as a string :param kwargs:
from browser import document
from visualife.core import HtmlViewport

drawing = HtmlViewport(document['svg-path'],300,100)
path_1 = [["M", 20, 50], ["C", 20,80, 80, 80, 80, 50]]
path_2 = [["M", 20, 20], ["L", 80, 20], ["L", 20, 50], ["L", 80, 50], ["L", 20, 80], ["L", 80, 80]]
path_3 = [["M", 20, 50], ["A", 50, 25, 0, 0, 1, 80, 80]]
path_style = {"fill": "none", "stroke": "#000", "stroke_linecap": "round",
      "stroke_linejoin": "round", "stroke_width": "5"}
drawing.rect("r1", 10, 10, 80, 80, stroke='black', stroke_width='1', fill='gainsboro')
drawing.path("p1", path_1, **path_style)
drawing.rect("r2", 110, 10, 80, 80, stroke='black', stroke_width='1', fill='gainsboro')
drawing.path("p2", path_2, **path_style, translate=[100, 0])
drawing.rect("r3", 210, 10, 80, 80, stroke='black', stroke_width='1', fill='gainsboro')
drawing.path("p3", path_3, **path_style, translate=[200, 0])
drawing.close()
polygon(id_str, points, **kwargs)
polyline(id_str, *points, **kwargs)

Creates a <polyline> element

Parameters:
  • id_str – (string) string to be used as the ID of the element
  • points – (list((number,number))) a list of points; each point must be a two-element tuple or list
  • kwargs – parameters to prepare style attributes
from random import random
from browser import document
from visualife.core import HtmlViewport

drawing = HtmlViewport(document['svg-polyline'],600,150)
rho = 0.5
p = [[0,0]]
for i in range(1, 100):
    p.append([i*6, p[-1][1]*(1-rho) + rho*(1-2*random())])
for pi in p: pi[1] = pi[1]*50 + 75
drawing.polyline("polyline", p, fill="none", stroke_width=1)
drawing.close()
radial_gradient(id_str, stop1, stop2, **kwargs)

Adds radial gradient to an element with a given id

Parameters:
  • id_str – id of a element you want to add radial gradient
  • stop1 – list or a tuple with first stop in the order [offset,color,opacity]
  • stop2 – list or a tuple with second stop in the order [offset,color,opacity]
Keyword Arguments:
 
  • cx (string) – This attribute defines the x coordinate of the end circle of the radial gradient, default is “50%”
  • cy (number) – This attribute defines the y coordinate of the end circle of the radial gradient, default is “50%”
  • fx (string) – This attribute defines the x coordinate of the start circle of the radial gradient, default is “50%”
  • fy (string) – This attribute defines the y coordinate of the start circle of the radial gradient, default is “50%”
  • r (string) – This attribute defines the radius of the end circle of the radial gradient.
rect(id_str, x, y, w, h, **kwargs)

Creates a <rect> element

Parameters:
  • id_str – (string) to be used as the ID of the element
  • x – (number) x coordinate of the top left corner
  • y – (number) y coordinate of the top left corner
  • w – (number) width of the rectangle
  • h – (number) height of the rectangle
  • kwargs – see below
Keyword Arguments:
 
  • rx (number) – x radius for rounded corners
  • ry (number) – y radius for rounded corners
  • angle (number) – angle to rotate the rectangle around its center (in degrees!)

Keyword arguments dictionary is also passed to a visualife.core.styles.create_style() method to prepare a style for drawing

from random import shuffle, random
from browser import document
from visualife.core import HtmlViewport
from visualife.core.styles import rgb_to_hex

drawing = HtmlViewport(document['svg-rect'],600,150)
n_x, n_y = 20, 5
points = [(i,j) for i in range(n_x) for j in range(n_y)]
shuffle(points)
for i, j in points:
      drawing.rect("r-%d-%d" % (i, j), i*30, j*30, 25 + random()*10, 25 + random()*10, stroke="darker",
        fill=rgb_to_hex((255, i*255/n_x, j*255/n_y)), angle=(10-random()*20), fill_opacity=random())
drawing.close()
rhomb(id_str, x, y, r, **kwargs)

Draws a rhomb

Parameters:
  • id_str – (string) - id string of a created element
  • x – x coordinate for this element
  • y – y coordinate for this element
  • r – radius value
rhomb_group(gid, x, y, c, r, **kwargs)

Group of rhombs drawn in a single batch.

This method has been devised to draw rhombs efficiently. All the rhombs will be placed in a single group. Graphics parameters from **kwargs fill be assigned to the group element. Therefore this method does not allow styling each square separately except its radius and color.

Parameters:
  • gid – (string) id assigned to the whole group of rhombs
  • x – (list(float)) list of X coordinates
  • y – (list(float)) list of Y coordinates
  • c – (color or list(color)) list of colors for rhombs or a single color - the same for all rhombs
  • r – (float) side width - the same for all rhombs
  • kwargs – other graphics parameters assigned to this group rather than separately to each rhomb
scale_x()

Returns a factor used to transform drawing X coordinates to internal SVG coordinates (X axis)

Factor lower than 1.0 means that X range requested for this object is wider than actual width of the SVG element A shape of a given width (say, 50) is multiplied by this factor prior drawing, so if the scale is 1/2 the drawn shape will be 25 in width

scale_y()

Returns a factor used to transform drawing Y coordinates to internal SVG coordinates (Y axis)

Factor lower than 1.0 means that Y range requested for this object is longer than actual height of the SVG element A shape of a given height (say, 50) is multiplied by this factor prior drawing, so if the scale is 1/2 the drawn shape will be 25 in height

set_background(color)

Sets the background color - will be applied in the next clear() method call

set_viewbox(x0, y0, w, h)

Sets viewbox parameters

square(id_str, x, y, a, **kwargs)

Creates a square as <rect> element

Parameters:
  • id_str – string to be used as the ID of the element
  • x – (number) x coordinate of the center
  • y – (number) y coordinate of the center
  • a – (number) side length
  • kwargs – see below
Keyword Arguments:
 
  • rx (number) – x radius for rounded corners
  • ry (number) – y radius for rounded corners
  • angle (number) – angle to rotate the rectangle around its center

Keyword arguments dictionary is also passed to a visualife.core.styles.create_style() method to prepare a style for drawing

squares_grid(gid, x0, y0, w, h, rows, columns, **kwargs)

Draws a grid of rectangles.

This method is intended to draws a grid of <rect> shapes as quickly as possible. Every rectangle has the same dimensions. They also have no color, which is to be applied later with DOM API. A rectangle of the grid in i-th column and j-th row (along X and Y axis, respectively) is assigned gid-i-j ID, where gid is the ID of the whole group.

Parameters:
  • id_str – (string) unique ID string for the group containing rectangles
  • x0 – X coordinate of the top left corner of the rectangle bounding the grid
  • y0 – Y coordinate of the top left corner of the rectangle bounding the grid
  • w – width of each rectangle
  • h – height of each rectangle
  • rows – number of rows of rectangles
  • columns – number of columns of rectangles
  • kwargs – see below
Keyword Arguments:
 
  • margin (value) – separation between rectangles
  • xmargin (value) – separation between rectangles along X axis
  • ymargin (value) – separation between rectangles along Y axis

All other arguments are passed to group construction method of the viewer

from math import sin, cos
from browser import document
from visualife.core.styles import colormap_by_name
from visualife.core import HtmlViewport

drawing = HtmlViewport(document['svg-rect-grid'],630,150)
drawing.squares_grid("grid", 2, 2, 4, 4, 126, 32, margin=1, stroke_width=0)
drawing.close()
palette = colormap_by_name("pinks", -1, 1)
for i in range(126):
    for j in range(32):
        z = sin(i/20)*cos(j/10)
        document["grid-"+str(i)+"-"+str(j)].style.fill = str(palette.color(z))
squares_group(gid, x, y, c, a, **kwargs)

Group of squares drawn in a single batch.

This method has been devised to draw squares efficiently. All the squares will be placed in a single group. Graphics parameters from **kwargs fill be assigned to the group element. Therefore this method does not allow styling each square separately except its radius and color.

Parameters:
  • gid – (string) id assigned to the whole group of squares
  • x – (list(float)) list of X coordinates
  • y – (list(float)) list of Y coordinates
  • c – (color or list(color)) list of colors for squares or a single color - the same for all squares
  • a – (float or list(float)) list of sides for squares or a single radii - the same for all squares
  • kwargs – other graphics parameters assigned to this group rather than separately to each one
start_clip_path(id_str)

Start a clipping path

Anything that will be drawn on this viewport since now, will be recorded as a clipping path identified by a given ID string. That content can be used to clip other graphical elements, but itself will not be visible on the screen.

A clipping path restricts the region to which drawing can be applied. Any part of the drawing that lie outside of the region bounded by the clipping path will not be drawn.

Remember to use close_clip_path() method to close this clipping path before doing anything else! Also note, that in the current implementation of the VL library only a group may be clipped.

Parameters:id_str – (string) a unique string that identifies this clipping path
from browser import document
from visualife.core import HtmlViewport
from visualife.core.styles import color_name_to_hex

drawing = HtmlViewport(document['svg-clip'],200,200)

drawing.start_clip_path("clip")
for ix, iy in [(50, 50), (150, 50), (50, 150), (150, 150)]:
  drawing.circle("circ-%d-%d" % (ix, iy), ix, iy, 50)
drawing.close_clip_path()

drawing.start_group("g-rect", clip_path="clip")   # Note: VL can clip only a group!
drawing.rect("rect1", 50, 50, 100, 100, stroke_width=3,
    fill=color_name_to_hex("LightSteelBlue"), stroke=color_name_to_hex("LightSlateGrey"))
drawing.close_group()
drawing.close()
start_group(id_str, **kwargs)

Start a new group

Anything that will be drawn on this viewport since now, will be included in a group identified by a given ID string. A group may have its own styling parameters or a clipping path; they can be passed to this methods with **kwargs. Use close_group() method to close this group.

Parameters:id_str – (string) a unique string that identifies this group
start_marker(id_str, view_box, ref_x, ref_y, width, height, orient='auto')

Start a marker definition

Anything that will be drawn on this viewport since now, will be recorded as a definition of a new marker.

Remember to use close_marker() method to close this marker definition!

Parameters:
  • id_str – (string) a unique string that identifies this clipping path
  • view_box – (string or list) defines a viewport for this marker
  • ref_x – (number) defines the X coordinate for the reference point of the marker, i.e. the point by which this marker will be attached to its line
  • ref_y – (number) defines the Y coordinate for the reference point of the marker, i.e. the point by which this marker will be attached to its line
  • width – (number) width of the marker viewport
  • height – (number) height of the marker viewport
  • orient"auto" or "auto-start-reverse"
from browser import document
from visualife.core import HtmlViewport

drawing = HtmlViewport(document['svg-marker'],300,100)

drawing.start_marker("arrowhead", "0 0 10 10", 5, 5, 5, 5)
drawing.path("arrowpath", [['M', 0, 0], ['L', 10, 5], ['L', 0, 10], ['z']])
drawing.close_marker()
drawing.line("l1", 145, 48, 10, 10, marker_end="arrowhead")
drawing.line("l1", 149, 50, 10, 90, marker_end="arrowhead")
drawing.line("l1", 153, 52, 250, 10, marker_end="arrowhead")
drawing.line("l1", 155, 55, 250, 90, marker_end="arrowhead")
drawing.close()
text(id_str, x, y, text, **kwargs)

Adds text to the viewport

Parameters:
  • id_str – id string of an element you want to add text to
  • x – x coordinate for text
  • y – y coordinate for text
  • text – text to write - string or list(string) - in this case every list element will be written in a new line
  • kwargs – styling parameters; see create_style() function for the list of accepted keywords

The example below illustrates, how to set up style for text. Note, how text_anchor property works! The allowed values are: start, middle and end. The small red dots marks the reference point for each text line i.e. the coordinates sent to the text() method.

from browser import document
from visualife.core import HtmlViewport

drawing = HtmlViewport(document['try-text'],0,0,600,110)
fox_sentence = "The quick brown fox jumps over the lazy dog"
drawing.text('txt1', 100, 10, fox_sentence, font_size=10, text_anchor='end')
drawing.text('txt1', 100, 25, fox_sentence, font_size=10, text_anchor='start')
drawing.text('txt1', 100, 40, fox_sentence, font_size=10, text_anchor='middle')
drawing.text('txt2', 100, 65, fox_sentence, font_size=15, font_family="monospace", text_anchor='start')
drawing.text('txt3', 100, 90, fox_sentence, font_size=20, font_style="italic", text_anchor='start')
for y in [10, 25, 45, 70]:
      drawing.circle("c"+str(y), 100, y, 1.5, fill='red', stroke="darker")
drawing.close()
text_length(text, **kwargs)

Measures the dimensions (in pixels) of a text as it would appear on a page

Parameters:
  • text – text to be drawn
  • kwargs – styling parameters as to be sent to SvgViewport.text() method
Returns:

width and height of the text element, in pixels

triangle(id_str, x, y, r, **kwargs)

Draws a triangle

Parameters:
  • id_str – id string of a created element
  • x – x coordinate for this element
  • y – y coordinate for this element
  • r – radius value
triangle_group(gid, x, y, c, r, **kwargs)

Group of triangles drawn in a single batch.

This method has been devised to draw triangles efficiently. All the triangles will be placed in a single group. Graphics parameters from **kwargs fill be assigned to the group element. Therefore this method does not allow styling each square separately except its radius and color.

Parameters:
  • gid – (string) id assigned to the whole group of triangles
  • x – (list(float)) list of X coordinates
  • y – (list(float)) list of Y coordinates
  • c – (color or list(color)) list of colors for triangles or a single color - the same for all triangles
  • r – (float) length of the side of a triangle - the same for all triangles
  • kwargs – other graphics parameters assigned to this group rather than separately to each triangle
viewport_name()

Returns the name if this viewport, which is always “HTML”

The method allows dynamic distinction between SVG and HTML viewports