drawsvg icon indicating copy to clipboard operation
drawsvg copied to clipboard

DrawingDef usage

Open liquidcarbon opened this issue 4 years ago • 4 comments

# Subclass DrawingDef if it must go between <def></def> tags in an SVG

Hi, can you please provide an example of using this? I'd like to define a few elements so that the final result looks like this:

  <defs>
    <!-- everything starts with a single bond -->
    <line id="bond" x1="0" y1="0" x2="60" y2="0" />
  </defs>

I can see that DrawingDef inherits from DrawingParentElement, and then... I'm lost.

liquidcarbon avatar Jun 06 '21 03:06 liquidcarbon

Elements that are not appended to the drawing but are referenced by other elements will automatically be included in <defs></defs>.

Example:

import drawSvg as draw
d = draw.Drawing(100, 100)

# Do not append `bond` to the drawing
bond = draw.Line(0, 0, 10, 10, stroke='black')

# `bond` is automatically added into <defs>
# A default `id` is generated if one isn't set
d.append(draw.Use(bond, 20, 50))
d.append(draw.Use(bond, 50, 50))
d.append(draw.Use(bond, 80, 50))

print(d.asSvg())
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
     width="100" height="100" viewBox="0 -100 100 100">
<defs>
<path d="M0,0 L10,-10" stroke="black" id="d0" />
</defs>
<use xlink:href="#d0" x="20" y="-50" />
<use xlink:href="#d0" x="50" y="-50" />
<use xlink:href="#d0" x="80" y="-50" />
</svg>

An example of this should probably be added to the documentation.

cduck avatar Jun 06 '21 04:06 cduck

Thank you! Is there a reason you use xlink:href ? Could it be replaced with just href? https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href

liquidcarbon avatar Jun 06 '21 05:06 liquidcarbon

Note: SVG 2 removed the need for the xlink namespace, so instead of xlink:href you should use href.

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href

drawSvg primarily supports SVG 1.1 and I believe CairoSVG (used for PNG output) doesn't recognize href.

cduck avatar Jun 06 '21 22:06 cduck

Leaving this open until I add an example to the documentation.

cduck avatar Jun 06 '21 22:06 cduck