Let's say I want to create a
donut gauge to display progress on an action. Something that looks like this:
[View Code]
By itself, it looks nice and all, but not really useful. We can make this useful by turning it into an SVG widget.
To widgetize this, the first thing we need to think about is what are its properties. In svidget, we refer to these as
params.
For our donut gauge our params will be:
- data - this is the primary data. Let this be a value between 0 and 1 representing a percentage.
- color - The color of the foreground on the circle.
- backColor - The color of the background on the circle.
- textColor - The color of the text in the middle.
- showText - A bool flag whether to show the text at all.
- width - The width of the donut. Can be a value between 1 and 98.
Svidget uses a declarative syntax to add parameters to a widget. Since SVG is structured XML we can extend it with the svidget namespace.
[View Code]
One key feature is the binding attribute. Here we can use
CSS selector syntax (+ attributes)
to map a parameter directly to an element or attribute in the SVG body. For more complex operations we can hook into events for the parameters when they
are set.
When we put it all together, our final widget code looks like this:
[View Code]
Now the fun part, using our donut gauge widget on a web page. Play around with the controls to interact with the widget.
The primary way to embed a widget on a web page is using an <object> tag.
The framework looks for all <object> tags with role="svidget" and instantiates the widget.
<object id="myDonutGauge" role="svidget" data="widgets/donut.svg" type="image/svg+xml" width="200" height="200">
<param name="data" value="0.55" />
<param name="color" value="#da3333" />
<param name="backColor" value="#ffac33" />
<param name="textColor" value="#da3333" />
<param name="showText" value="true" />
<param name="width" value="40" />
</object>
[View Code]
You can also load a widget programmatically:
svidget.load("#widgetContainer", "widgets/donut.svg", {
data: 0.55,
color: "#da3333",
backColor: "#ffac33",
textColor: "#da3333",
showText: true,
width: 40,
});
[View Code]