Search code examples
pythoncairopycairo

How to duplicate SVGSurface in Cairo (Python)


Say I have a surface and draw something on it.

surface = cairo.SVGSurface("foo.svg", 360, 240)

ctx = cairo.Context(surface)
ctx.move_to(0, 0)
ctx.line_to(0, 80)
ctx.line_to(80, 80)
ctx.fill()

How do I duplicate this surface so I can draw different shapes from where I left off?

surface_1 = [copy surface]
surface_2 = [copy surface]

# Draw something on surface_1
# Draw something different on surface_2

Solution

  • My suggestion: Create a new surface and draw your existing one to it.

    surface2 = cairo.SVGSurface("foo2.svg", 360, 240)
    ctx2 = cairo.Context(surface2)
    ctx2.save()
    ctx2.set_source_surface(surface)
    ctx2.set_operator("SOURCE")
    ctx2.paint()
    ctx2.restore()
    

    (Note that I have no idea how PyCairo maps the C API to Python, so the above is a guess that might not work)