Donner
C++20 SVG rendering library
Loading...
Searching...
No Matches
svg_tree_interaction.cc

SVG Tree Interaction.

SVG Tree InteractionDemonstrates how to interact with the SVG DOM. This example loads an SVG file, gets the SVGPathElement for a path in the image, then prints metadata and modifies it.

bazel run //examples:svg_tree_interaction
/**
* @example svg_tree_interaction.cc SVG Tree Interaction
*
* Demonstrates how to interact with the SVG DOM. This example loads an SVG file, gets the
* SVGPathElement for a path in the image, then prints metadata and modifies it.
*
* ```sh
* bazel run //examples:svg_tree_interaction
* ```
*/
#include <iostream>
#include "donner/svg/SVG.h"
int main(int argc, char* argv[]) {
//! [homepage_snippet]
//! [svg_string]
// This is the base SVG we are loading, a simple path containing a line
const std::string_view svgContents(R"(
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 10 10">
<path d="M 1 1 L 4 5" stroke="blue" />
</svg>
)");
//! [svg_string]
//! [svg_parse]
// Call ParseSVG to load the SVG file
ParseResult<donner::svg::SVGDocument> maybeResult =
//! [svg_parse]
//! [error_handling]
if (maybeResult.hasError()) {
std::cerr << "Parse Error " << maybeResult.error() << "\n"; // Includes line:column and reason
std::abort();
// - or - handle the error per your project's conventions
}
//! [error_handling]
//! [get_path]
donner::svg::SVGDocument document = std::move(maybeResult.result());
// querySelector supports standard CSS selectors, anything that's valid when defining a CSS rule
// works here too, for example querySelector("svg > path[fill='blue']") is also valid and will
// match the same element.
std::optional<donner::svg::SVGElement> maybePath = document.querySelector("path");
UTILS_RELEASE_ASSERT_MSG(maybePath.has_value(), "Failed to find path element");
// The result of querySelector is a generic SVGElement, but we know it's a path, so we can cast
// it. If the cast fails, an assertion will be triggered.
//! [get_path]
if (std::optional<donner::svg::PathSpline> spline = path.computedSpline()) {
std::cout << "Path: " << *spline << "\n";
std::cout << "Length: " << spline->pathLength() << " userspace units\n";
} else {
std::cout << "Path is empty\n";
}
//! [homepage_snippet]
// We could also use \ref SVGElement::isa<>() to check if the element is a path, and then cast it.
assert(maybePath->isa<donner::svg::SVGPathElement>());
// Set styles, note that these combine together and do not replace.
//! [path_set_style]
path.setStyle("fill: red");
path.setStyle("stroke: white");
// Get the parsed, cascaded style for this element and output it to the console.
std::cout << "Computed style: " << path.getComputedStyle() << "\n";
//! [path_set_style]
//! [add_circle]
// Add a circle to the document
circle.setCx(donner::Lengthd(5));
circle.setCy(donner::Lengthd(5));
circle.setR(donner::Lengthd(4));
circle.setStyle("color: #AAA");
document.svgElement().insertBefore(circle, path);
//! [add_circle]
return 0;
}
#define UTILS_RELEASE_ASSERT_MSG(x, msg)
An assert that evaluates on both release and debug builds and errors with the provided msg.
Definition Utils.h:102
A parser result, which may contain a result of type T, or an error, or both.
Definition ParseResult.h:17
DOM object for a "<circle>" element.
Definition SVGCircleElement.h:62
void setR(Lengthd value)
Set the radius.
Definition SVGCircleElement.cc:31
void setCx(Lengthd value)
Set the center X coordinate.
Definition SVGCircleElement.cc:17
void setCy(Lengthd value)
Set the center Y coordinate.
Definition SVGCircleElement.cc:24
static SVGCircleElement Create(SVGDocument &document)
Create a new "<circle>" element.
Definition SVGCircleElement.h:89
Represents an SVG document, which holds a collection of SVGElement as the document tree.
Definition SVGDocument.h:32
SVGSVGElement svgElement() const
Get the root "<svg>" element of the document.
Definition SVGDocument.cc:40
std::optional< SVGElement > querySelector(std::string_view selector)
Find the first element in the tree that matches the given CSS selector.
Definition SVGDocument.cc:65
Derived cast()
Cast this element to its derived type.
Definition SVGElement.h:315
const PropertyRegistry & getComputedStyle() const
Get the computed CSS style of this element, after the CSS cascade.
Definition SVGElement.cc:294
void setStyle(std::string_view style)
Set the element style, the value of the "style" attribute.
Definition SVGElement.cc:107
void insertBefore(const SVGElement &newNode, std::optional< SVGElement > referenceNode)
Insert newNode as a child, before referenceNode.
Definition SVGElement.cc:259
std::optional< PathSpline > computedSpline() const
Get the path spline, computed by converting this shape's path to a spline.
Definition SVGGeometryElement.cc:34
std::optional< double > pathLength() const
Get the path length override, if set. To get the computed path length, use computedPathLength().
Definition SVGGeometryElement.cc:18
DOM object for a "<path>" element.
Definition SVGPathElement.h:86
static ParseResult< SVGDocument > ParseSVG(std::string_view source, std::vector< ParseError > *outWarnings=nullptr, Options options={}, std::unique_ptr< ResourceLoaderInterface > resourceLoader=nullptr) noexcept
Parses an SVG XML document from a string (typically the contents of a .svg file).
Definition SVGParser.cc:270
Error context for a failed parse, such as the error reason, line, and character offset.
Definition ParseError.h:14