pythonvispy

How to draw multiple rectangles using Vispy?


I referred to this example : https://vispy.org/gallery/scene/polygon.html#sphx-glr-gallery-scene-polygon-py

I want to draw multiple same shaped rectangles, but I don't understand how to set the coordinates.

cx, cy = (0.2, 0.2)
halfx, halfy = (0.1, 0.1)

poly_coords = [(cx - halfx, cy - halfy),
               (cx + halfx, cy - halfy),
               (cx + halfx, cy + halfy),
               (cx - halfx, cy + halfy)]

The above draws a rectangle, however, when I add more coordinates as below:

from vispy import app
import sys
from vispy.scene import SceneCanvas
from vispy.scene.visuals import Polygon, Ellipse, Rectangle, RegularPolygon
from vispy.color import Color

white = Color("#ecf0f1")
gray = Color("#121212")
red = Color("#e74c3c")
blue = Color("#2980b9")
orange = Color("#e88834")

canvas = SceneCanvas(keys='interactive', title='Polygon Example',
                     show=True)
v = canvas.central_widget.add_view()
v.bgcolor = gray
v.camera = 'panzoom'

cx, cy = (0.2, 0.2)
halfx, halfy = (0.1, 0.1)

poly_coords = [(cx - halfx, cy - halfy),
               (cx + halfx, cy - halfy),
               (cx + halfx, cy + halfy),
               (cx - halfx, cy + halfy),
               
               (0.2+cx - halfx, 0.2+cy - halfy),
               (0.2+cx + halfx, 0.2+cy - halfy),
               (0.2+cx + halfx, 0.2+cy + halfy),
               (0.2+cx - halfx, 0.2+cy + halfy)]


poly = Polygon(poly_coords, color=red, border_color=white,border_width=3, parent=v.scene)

if __name__ == '__main__':
    if sys.flags.interactive != 1:
        app.run()

I get a strange shaped polygon, instead of 2 rectangles.

How could I set seperate rectangle coordinates and draw 2 different rectangles?


Solution

  • To draw multiple shapes, you need to explicitly create multiple shape objects. The example link draws different types of shapes, but you can equally create many of the same shape.

    Based on your example:

        poly_coords = [(cx - halfx, cy - halfy),
                   (cx + halfx, cy - halfy),
                   (cx + halfx, cy + halfy),
                   (cx - halfx, cy + halfy),]
        poly = Polygon(poly_coords, color=red, border_color=white,border_width=3, parent=v.scene)
    
        poly_coords = [
                   (0.2+cx - halfx, 0.2+cy - halfy),
                   (0.2+cx + halfx, 0.2+cy - halfy),
                   (0.2+cx + halfx, 0.2+cy + halfy),
                   (0.2+cx - halfx, 0.2+cy + halfy)]
        poly = Polygon(poly_coords, color=blue, border_color=white,border_width=3, parent=v.scene)
    

    For drawing rectangles, consider using the vispy Rectangle shape, which requires less coordinates to define and should be simpler to use.