Donner 0.5.0
Embeddable browser-grade SVG2 engine
Loading...
Searching...
No Matches
svg_text_interaction.cc

SVG Text DOM Manipulation.

SVG Text DOM Manipulation Demonstrates how to create, inspect, and modify <text> content through the Donner DOM. Builds a new SVG document from scratch containing a <text> element with multiple <tspan> runs, then queries, re-styles, and appends more content, and finally renders the result to a PNG.

bazel run //examples:svg_text_interaction -- output.png
/**
* @example svg_text_interaction.cc SVG Text DOM Manipulation
*
* Demonstrates how to create, inspect, and modify `<text>` content through the Donner DOM.
* Builds a new SVG document from scratch containing a `<text>` element with multiple
* `<tspan>` runs, then queries, re-styles, and appends more content, and finally renders the
* result to a PNG.
*
* ```sh
* bazel run //examples:svg_text_interaction -- output.png
* ```
*/
#include <iostream>
#include "donner/svg/SVG.h"
int main(int argc, char* argv[]) {
// Parse an initial document with one <text> element and two <tspan> runs. In a real
// application you would typically load this from a file, but the embedded snippet here
// keeps the example self-contained.
//! [text_svg_source]
const std::string_view kSvgSource(R"(
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="120" viewBox="0 0 400 120">
<text x="20" y="70" font-family="sans-serif" font-size="32" fill="#1f5a8a">
Hello, <tspan fill="#c33" font-weight="bold">Donner</tspan>!
</text>
</svg>
)");
//! [text_svg_source]
auto maybeDocument =
if (maybeDocument.hasError()) {
std::cerr << "Parse error: " << maybeDocument.error() << "\n";
return 1;
}
SVGDocument document = std::move(maybeDocument.result());
//! [text_query]
// Find the <text> element via a CSS selector and read its current content.
std::optional<SVGElement> maybeText = document.querySelector("text");
UTILS_RELEASE_ASSERT_MSG(maybeText, "Expected a <text> element in the document");
SVGTextElement text = maybeText->cast<SVGTextElement>();
std::cout << "Current text content: \"" << text.textContent() << "\"\n";
//! [text_query]
//! [text_restyle]
// Restyle the <text> element. Styles compose with any existing values instead of replacing
// them, so this leaves the inherited fill color on the nested <tspan> runs alone.
text.setStyle("font-size: 40px");
text.setStyle("font-weight: 500");
text.setX(Lengthd(20));
text.setY(Lengthd(80));
//! [text_restyle]
//! [text_append_tspan]
// Append a new <tspan> run to the end of the text. New elements are attached via the same
// DOM API used for shapes: create them, configure their properties, then insert them into
// the tree.
newRun.appendText(" v0.5");
newRun.setStyle("fill: #2a9");
newRun.setStyle("font-style: italic");
text.appendChild(newRun);
//! [text_append_tspan]
std::cout << "After append, text content: \"" << text.textContent() << "\"\n";
//! [text_render]
// Render the modified document to PNG.
const std::string output = argc >= 2 ? argv[1] : "text_interaction.png";
renderer.draw(document);
if (!renderer.save(output.c_str())) {
std::cerr << "Failed to save " << output << "\n";
return 1;
}
std::cout << "Rendered to " << output << " (" << renderer.width() << "x" << renderer.height()
<< ")\n";
//! [text_render]
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
Represents a parsed SVG document containing a tree of SVGElement nodes.
Definition SVGDocument.h:39
std::optional< SVGElement > querySelector(std::string_view selector)
Find the first element in the tree that matches the given CSS selector.
Definition SVGDocument.cc:75
DOM object for a "<tspan>" element.
Definition SVGTSpanElement.h:98
static SVGTSpanElement Create(SVGDocument &document)
Create a new "<tspan>" element within the specified document.
Definition SVGTSpanElement.h:127
DOM object for a "<text>" element.
Definition SVGTextElement.h:79
Collects parse warnings during parsing.
Definition ParseWarningSink.h:28
Backend-agnostic renderer that resolves to the active build backend (Skia or tiny-skia).
Definition Renderer.h:27
int height() const override
Returns the rendered height in pixels.
Definition Renderer.cc:131
bool save(const char *filename)
Saves the last rendered frame to a PNG file.
Definition Renderer.cc:116
void draw(SVGDocument &document) override
Draws the SVG document using the active backend.
Definition Renderer.cc:18
int width() const override
Returns the rendered width in pixels.
Definition Renderer.cc:127
Represents a parsed SVG document containing a tree of SVGElement nodes.
Definition SVGDocument.h:39
Represents a single SVG element (e.g., <rect>, <circle>, <g>, <text>, etc.) within an SVGDocument.
Definition SVGElement.h:52
Derived cast()
Cast this element to its derived type.
Definition SVGElement.h:330
void setStyle(std::string_view style)
Set the element style, the value of the "style" attribute.
Definition SVGElement.cc:199
void appendChild(const SVGElement &child)
Append child as a child of the current node.
Definition SVGElement.cc:413
DOM object for a "<tspan>" element.
Definition SVGTSpanElement.h:98
void appendText(std::string_view text)
Append text content from text or CDATA nodes.
Definition SVGTextContentElement.cc:167
RcString textContent() const
Get the raw text content concatenated from all child text nodes.
Definition SVGTextContentElement.cc:196
DOM object for a "<text>" element.
Definition SVGTextElement.h:79
void setY(std::optional< Lengthd > value)
Sets the y attribute list to a single value (absolute y-position).
Definition SVGTextPositioningElement.cc:40
void setX(std::optional< Lengthd > value)
Sets the x attribute list to a single value (absolute x-position).
Definition SVGTextPositioningElement.cc:12
static ParseResult< SVGDocument > ParseSVG(std::string_view source, ParseWarningSink &warningSink, Options options={}, SVGDocument::Settings settings={}) noexcept
Parses an SVG XML document from a string (typically the contents of a .svg file).
Definition SVGParser.cc:377
Length< double > Lengthd
Shorthand for Length<double>.
Definition Length.h:228