Git Product home page Git Product logo

svgo's Introduction

SVGo: A Go library for SVG generation

The library generates SVG as defined by the Scalable Vector Graphics 1.1 Specification (http://www.w3.org/TR/SVG11/). Output goes to the specified io.Writer.

Supported SVG elements and functions

Shapes, lines, text

circle, ellipse, polygon, polyline, rect (including roundrects), line, text

Paths

general, arc, cubic and quadratic bezier paths,

Image and Gradients

image, linearGradient, radialGradient,

Transforms

translate, rotate, scale, skewX, skewY

Animation

animate, animateMotion, animateTranslate, animateRotate, animateScale, animateSkewX, animateSkewY

Filter Effects

filter, feBlend, feColorMatrix, feColorMatrix, feComponentTransfer, feComposite, feConvolveMatrix, feDiffuseLighting, feDisplacementMap, feDistantLight, feFlood, feGaussianBlur, feImage, feMerge, feMorphology, feOffset, fePointLight, feSpecularLighting, feSpotLight,feTile, feTurbulence

Metadata elements

desc, defs, g (style, transform, id), marker, mask, pattern, title, (a)ddress, link, script, use

Building and Usage

See svgdef.[svg|png|pdf] for a graphical view of the function calls

Usage: (assuming GOPATH is set)

go get github.com/ajstarks/svgo
go install github.com/ajstarks/svgo/...

You can use godoc to browse the documentation from the command line:

$ go doc github.com/ajstarks/svgo

a minimal program, to generate SVG to standard output.

package main

import (
	"github.com/ajstarks/svgo"
	"os"
)

func main() {
	width := 500
	height := 500
	canvas := svg.New(os.Stdout)
	canvas.Start(width, height)
	canvas.Circle(width/2, height/2, 100)
	canvas.Text(width/2, height/2, "Hello, SVG", "text-anchor:middle;font-size:30px;fill:white")
	canvas.End()
}

Drawing in a web server: (http://localhost:2003/circle)

package main

import (
	"log"
	"github.com/ajstarks/svgo"
	"net/http"
)

func main() {
	http.Handle("/circle", http.HandlerFunc(circle))
	err := http.ListenAndServe(":2003", nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func circle(w http.ResponseWriter, req *http.Request) {
  w.Header().Set("Content-Type", "image/svg+xml")
  s := svg.New(w)
  s.Start(500, 500)
  s.Circle(250, 250, 125, "fill:none;stroke:black")
  s.End()
}

You may view the SVG output with a browser that supports SVG (tested on Chrome, Opera, Firefox and Safari), or any other SVG user-agent such as Batik Squiggle.

Graphics Sketching with SVGo and svgplay

Combined with the svgplay command, SVGo can be used to "sketch" with code in a browser.

To use svgplay and SVGo, first go to a directory with your code, and run:

$ svgplay
2014/06/25 22:05:28 ☠ ☠ ☠ Warning: this server allows a client connecting to 127.0.0.1:1999 to execute code on this computer ☠ ☠ ☠	

Next open your browser to the svgplay server you just started. svgplay only listens on localhost, and uses port 1999 (guess which year SVG was first introduced) by default

http://localhost:1999/

Enter your code in the textarea, and when you are ready to run press Shift--Enter. The code will be compiled, with the results on the right. To update, change the code and repeat. Note that compilation errors are shown in red under the code. In order for svgplay/SVGo to work, make sure that the io.Writer specified with the New function is os.Stdout.

If you want to sketch with an existing file, enter its URL:

http://localhost:1999/foo.go

SVGplay

SVGo Papers and presentations

Tutorial Video

A video describing how to use the package can be seen on YouTube at http://www.youtube.com/watch?v=ze6O2Dj5gQ4

Package contents

  • svg.go: Library
  • newsvg: Coding template command
  • svgdef: Creates a SVG representation of the API
  • animate: Animation demo
  • am: Animate motion demo
  • amt: Animate transformation demo
  • android: The Android logo
  • bubtrail: Bubble trails
  • bulletgraph: Bullet Graphs (via Stephen Few)
  • colortab: Display SVG named colors with RGB values
  • compx: Component diagrams
  • flower: Random "flowers"
  • fontcompare: Compare two fonts
  • f50: Get 50 photos from Flickr based on a query
  • fe: Filter effects
  • funnel: Funnel from transparent circles
  • gradient: Linear and radial gradients
  • html5logo: HTML5 logo with draggable elements
  • imfade: Show image fading
  • lewitt: Version of Sol Lewitt's Wall Drawing 91
  • ltr: Layer Tennis Remixes
  • marker: Test markers
  • paths: Demonstrate SVG paths
  • pattern: Test patterns
  • planets: Show the scale of the Solar system
  • pmap: Proportion maps
  • randcomp: Compare random number generators
  • richter: Gerhard Richter's 256 colors
  • rl: Random lines (port of a Processing demo)
  • skewabc: Skew ABC
  • span: Text span
  • stockproduct: Visualize product and stock prices
  • svgopher: SVGo Mascot
  • svgplay: SVGo sketching server
  • svgplot: Plot data
  • svgrid: Compose SVG files in a grid
  • tsg: Twitter Search Grid
  • tumblrgrid: Tumblr picture grid
  • turbulence: Turbulence filter effect
  • vismem: Visualize data from files
  • webfonts: "Hello, World" with Google Web Fonts
  • websvg: Generate SVG as a web server

Functions and types

Many functions use x, y to specify an object's location, and w, h to specify the object's width and height. Where applicable, a final optional argument specifies the style to be applied to the object. The style strings follow the SVG standard; name:value pairs delimited by semicolons, or a series of name="value" pairs. For example: "fill:none; opacity:0.3" or fill="none" opacity="0.3" (see: http://www.w3.org/TR/SVG11/styling.html)

The SVG type:

type SVG struct {
    Writer   io.Writer
}

Most operations are methods on this type, specifying the destination io.Writer.

The Offcolor type:

type Offcolor struct {
	Offset  uint8
	Color   string
	Opacity float64
}

is used to specify the offset, color, and opacity of stop colors in linear and radial gradients

The Filterspec type:

type Filterspec struct {
	In string
	In2 string
	Result string
}

is used to specify inputs and results for filter effects

Structure, Scripting, Metadata, Transformation and Links

New(w io.Writer) *SVG

Constructor, Specify the output destination.

Start(w int, h int, attributes ...string)

begin the SVG document with the width w and height h. Optionally add additional elements (such as additional namespaces or scripting events) http://www.w3.org/TR/SVG11/struct.html#SVGElement

Startview(w, h, minx, miny, vw, vh int)

begin the SVG document with the width w, height h, with a viewBox at minx, miny, vw, vh. http://www.w3.org/TR/SVG11/struct.html#SVGElement

Startunit(w int, h int, unit string, ns ...string)

begin the SVG document, with width and height in the specified units. Optionally add additional elements (such as additional namespaces or scripting events) http://www.w3.org/TR/SVG11/struct.html#SVGElement

Startpercent(w int, h int, ns ...string)

begin the SVG document, with width and height in percent. Optionally add additional elements (such as additional namespaces or scripting events) http://www.w3.org/TR/SVG11/struct.html#SVGElement

StartviewUnit(w, h int, unit string, minx, miny, vw, vh int)

begin the SVG document with the width w, height h, in the specified unit, with a viewBox at minx, miny, vw, vh. http://www.w3.org/TR/SVG11/struct.html#SVGElement

End()

end the SVG document

Script(scriptype string, data ...string)

Script defines a script with a specified type, (for example "application/javascript"). if the first variadic argument is a link, use only the link reference. Otherwise, treat variadic arguments as the text of the script (marked up as CDATA). if no data is specified, simply close the script element. http://www.w3.org/TR/SVG/script.html

Style(scriptype string, data ...string)

Style defines a script with a specified type, (for example "text/css"). if the first variadic argument is a link, use only the link reference. Otherwise, treat variadic arguments as the text of the script (marked up as CDATA). if no data is specified, simply close the style element. https://www.w3.org/TR/SVG/styling.html#StyleElement

Group(s ...string)

begin a group, with arbitrary attributes http://www.w3.org/TR/SVG11/struct.html#GElement

Gstyle(s string)

begin a group, with the specified style. http://www.w3.org/TR/SVG11/struct.html#GElement

Gid(s string)

begin a group, with the specified id.

Gtransform(s string)

begin a group, with the specified transform, end with Gend(). http://www.w3.org/TR/SVG11/coords.html#TransformAttribute

Translate(x, y int)

begins coordinate translation to (x,y), end with Gend(). http://www.w3.org/TR/SVG11/coords.html#TransformAttribute

Scale(n float64)

scales the coordinate system by n, end with Gend(). http://www.w3.org/TR/SVG11/coords.html#TransformAttribute

ScaleXY(x, y float64)

scales the coordinate system by x, y. End with Gend(). http://www.w3.org/TR/SVG11/coords.html#TransformAttribute

SkewX(a float64)

SkewX skews the x coordinate system by angle a, end with Gend(). http://www.w3.org/TR/SVG11/coords.html#TransformAttribute

SkewY(a float64)

SkewY skews the y coordinate system by angle a, end with Gend(). http://www.w3.org/TR/SVG11/coords.html#TransformAttribute

SkewXY(ax, ay float64)

SkewXY skews x and y coordinate systems by ax, ay respectively, end with Gend(). http://www.w3.org/TR/SVG11/coords.html#TransformAttribute

Rotate(r float64)

rotates the coordinate system by r degrees, end with Gend(). http://www.w3.org/TR/SVG11/coords.html#TransformAttribute

TranslateRotate(x, y int, r float64)

translates the coordinate system to (x,y), then rotates to r degrees, end with Gend().

RotateTranslate(x, y int, r float64)

rotates the coordinate system r degrees, then translates to (x,y), end with Gend().

Gend()

end the group (must be paired with Gstyle, Gtransform, Gid).

ClipPath(s ...string)

Begin a ClipPath http://www.w3.org/TR/SVG/masking.html#ClippingPaths

ClipEnd()

End a ClipPath http://www.w3.org/TR/SVG/masking.html#ClippingPaths

Def()

begin a definition block. http://www.w3.org/TR/SVG11/struct.html#DefsElement

DefEnd()

end a definition block.

Marker(id string, x, y, w, h int, s ...string)

define a marker http://www.w3.org/TR/SVG11/painting.html#MarkerElement

MarkerEnd()

end a marker

Mask(id string, x int, y int, w int, h int, s ...string)

creates a mask with a specified id, dimension, and optional style. http://www.w3.org/TR/SVG/masking.html

MaskEnd()

ends the Mask element.

Pattern(id string, x, y, width, height int, putype string, s ...string)

define a Pattern with the specified dimensions, the putype can be either "user" or "obj", which sets the patternUnits attribute to be either userSpaceOnUse or objectBoundingBox. http://www.w3.org/TR/SVG11/pservers.html#Patterns

Desc(s string)

specify the text of the description. http://www.w3.org/TR/SVG11/struct.html#DescElement

Title(s string)

specify the text of the title. http://www.w3.org/TR/SVG11/struct.html#TitleElement

Link(href string, title string)

begin a link named "href", with the specified title. http://www.w3.org/TR/SVG11/linking.html#Links

LinkEnd()

end the link.

Use(x int, y int, link string, s ...string)

place the object referenced at link at the location x, y. http://www.w3.org/TR/SVG11/struct.html#UseElement

Shapes

Circle(x int, y int, r int, s ...string)

draw a circle, centered at x,y with radius r. http://www.w3.org/TR/SVG11/shapes.html#CircleElement

Circle

Ellipse(x int, y int, w int, h int, s ...string)

draw an ellipse, centered at x,y with radii w, and h. http://www.w3.org/TR/SVG11/shapes.html#EllipseElement

Ellipse

Polygon(x []int, y []int, s ...string)

draw a series of line segments using an array of x, y coordinates. http://www.w3.org/TR/SVG11/shapes.html#PolygonElement

Polygon

Rect(x int, y int, w int, h int, s ...string)

draw a rectangle with upper left-hand corner at x,y, with width w, and height h. http://www.w3.org/TR/SVG11/shapes.html#RectElement

Rect

CenterRect(x int, y int, w int, h int, s ...string)

draw a rectangle with its center at x,y, with width w, and height h.

Roundrect(x int, y int, w int, h int, rx int, ry int, s ...string)

draw a rounded rectangle with upper the left-hand corner at x,y, with width w, and height h. The radii for the rounded portion is specified by rx (width), and ry (height).

Roundrect

Square(x int, y int, s int, style ...string)

draw a square with upper left corner at x,y with sides of length s.

Square

Paths

Path(p string, s ...style)

draw the arbitrary path as specified in p, according to the style specified in s. http://www.w3.org/TR/SVG11/paths.html

Arc(sx int, sy int, ax int, ay int, r int, large bool, sweep bool, ex int, ey int, s ...string)

draw an elliptical arc beginning coordinate at sx,sy, ending coordinate at ex, ey width and height of the arc are specified by ax, ay, the x axis rotation is r

if sweep is true, then the arc will be drawn in a "positive-angle" direction (clockwise), if false, the arc is drawn counterclockwise.

if large is true, the arc sweep angle is greater than or equal to 180 degrees, otherwise the arc sweep is less than 180 degrees. http://www.w3.org/TR/SVG11/paths.html#PathDataEllipticalArcCommands

Arc

Bezier(sx int, sy int, cx int, cy int, px int, py int, ex int, ey int, s ...string)

draw a cubic bezier curve, beginning at sx,sy, ending at ex,ey with control points at cx,cy and px,py. http://www.w3.org/TR/SVG11/paths.html#PathDataCubicBezierCommands

Bezier

Qbezier(sx int, sy int, cx int, cy int, ex int, ey int, tx int, ty int, s ...string)

draw a quadratic bezier curve, beginning at sx, sy, ending at tx,ty with control points are at cx,cy, ex,ey. http://www.w3.org/TR/SVG11/paths.html#PathDataQuadraticBezierCommands

Qbezier

Qbez(sx int, sy int, cx int, cy int, ex int, ey int, s...string)

draws a quadratic bezier curver, with optional style beginning at sx,sy, ending at ex, sy with the control point at cx, cy. http://www.w3.org/TR/SVG11/paths.html#PathDataQuadraticBezierCommands

Qbez

Lines

Line(x1 int, y1 int, x2 int, y2 int, s ...string)

draw a line segment between x1,y1 and x2,y2. http://www.w3.org/TR/SVG11/shapes.html#LineElement

Line

Polyline(x []int, y []int, s ...string)

draw a polygon using coordinates specified in x,y arrays. http://www.w3.org/TR/SVG11/shapes.html#PolylineElement

Polyline

Image and Text

Image(x int, y int, w int, h int, link string, s ...string)

place at x,y (upper left hand corner), the image with width w, and height h, referenced at link. http://www.w3.org/TR/SVG11/struct.html#ImageElement

Image

Text(x int, y int, t string, s ...string)

Place the specified text, t at x,y according to the optional style specified in s. http://www.w3.org/TR/SVG11/text.html#TextElement

Textspan(x int, y int, t string, s ...string)

Place specified text, t at x,y according to the optional style specified in s. https://www.w3.org/TR/SVG11/text.html#TSpanElement Use this method with Span(...). End with TextEnd()

Span(t string, s ...string)

Create a text span t, using optional style s

TextEnd()

End a text span

Textlines(x, y int, s []string, size, spacing int, fill, align string)

Places lines of text in s, starting at x,y, at the specified size, fill, and alignment, and spacing.

Textpath(t string, pathid string, s ...string)

places optionally styled text along a previously defined path. http://www.w3.org/TR/SVG11/text.html#TextPathElement Image

Color

RGB(r int, g int, b int) string

creates a style string for the fill color designated by the (r)ed, g(reen), (b)lue components. http://www.w3.org/TR/css3-color/

RGBA(r int, g int, b int, a float64) string

as above, but includes the color's opacity as a value between 0.0 (fully transparent) and 1.0 (opaque).

Gradients

LinearGradient(id string, x1, y1, x2, y2 uint8, sc []Offcolor)

constructs a linear color gradient identified by id, along the vector defined by (x1,y1), and (x2,y2). The stop color sequence defined in sc. Coordinates are expressed as percentages. http://www.w3.org/TR/SVG11/pservers.html#LinearGradients LinearGradient

RadialGradient(id string, cx, cy, r, fx, fy uint8, sc []Offcolor)

constructs a radial color gradient identified by id, centered at (cx,cy), with a radius of r. (fx, fy) define the location of the focal point of the light source. The stop color sequence defined in sc. Coordinates are expressed as percentages. http://www.w3.org/TR/SVG11/pservers.html#RadialGradients

RadialGradient

Animation

Animate(link, attr string, from, to int, duration float64, repeat int, s ...string)

Animate animates the item referenced by the link, using the specified attribute The animation starts at coordinate from, terminates at to, and repeats as specified. Addtional attributes may be added as needed. https://www.w3.org/TR/SVG11/animate.html#AnimateElement

AnimateMotion(link, path string, duration float64, repeat int, s ...string) 

AnimateMotion animates the referenced object link along the specified path https://www.w3.org/TR/SVG11/animate.html#AnimateMotionElement

AnimateTranslate(link string, fx, fy, tx, ty int, duration float64, repeat int, s ...string)

AnimateTranslate animates the translation transformation (link refers to the object to animate, fx, fy are from coordinates, tx, ty are the to coordinates) https://www.w3.org/TR/SVG11/animate.html#AnimateTransformElement

AnimateRotate(link string, fs, fc, fe, ts, tc, te int, duration float64, repeat int, s ...string)

AnimateRotate animates the rotation transformation (link refers to the object to animate, f[s,c,e] are the from start, center, and end angles, t[s,c,e] are the start, center, and end angles) https://www.w3.org/TR/SVG11/animate.html#AnimateTransformElement

AnimateScale(link string, from, to, duration float64, repeat int, s ...string)

AnimateScale animates the scale transformation (link refers to the object to animate, from and to specify the scaling factor) https://www.w3.org/TR/SVG11/animate.html#AnimateTransformElement

AnimateSkewX(link string, from, to, duration float64, repeat int, s ...string)

AnimateSkewX animates the skewX transformation ((link refers to the object to animate, from and to specify the skew angle) https://www.w3.org/TR/SVG11/animate.html#AnimateTransformElement

AnimateSkewY(link string, from, to, duration float64, repeat int, s ...string)

AnimateSkewY animates the skewY transformation (link refers to the object to animate, and from and to specify the skew angle) https://www.w3.org/TR/SVG11/animate.html#AnimateTransformElement

Filter Effects

Filter(id string, s ...string)

Filter begins a filter set Standard reference: http://www.w3.org/TR/SVG11/filters.html#FilterElement

Fend() 

Fend ends a filter set Standard reference: http://www.w3.org/TR/SVG11/filters.html#FilterElement

FeBlend(fs Filterspec, mode string, s ...string) 

FeBlend specifies a Blend filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feBlendElement

FeColorMatrix(fs Filterspec, values [20]float64, s ...string)	

FeColorMatrix specifies a color matrix filter primitive, with matrix values Standard reference: http://www.w3.org/TR/SVG11/filters.html#feColorMatrixElement

FeColorMatrixHue(fs Filterspec, value float64, s ...string)  	

FeColorMatrix specifies a color matrix filter primitive, with hue values Standard reference: http://www.w3.org/TR/SVG11/filters.html#feColorMatrixElement

FeColorMatrixSaturate(fs Filterspec, value float64, s ...string) 

FeColorMatrix specifies a color matrix filter primitive, with saturation values Standard reference: http://www.w3.org/TR/SVG11/filters.html#feColorMatrixElement

FeColorMatrixLuminence(fs Filterspec, s ...string) 

FeColorMatrix specifies a color matrix filter primitive, with luminence values Standard reference: http://www.w3.org/TR/SVG11/filters.html#feColorMatrixElement

FeComponentTransfer()  	

FeComponentTransfer begins a feComponent filter Element> Standard reference: http://www.w3.org/TR/SVG11/filters.html#feComponentTransferElement

FeCompEnd()

FeCompEnd ends a feComponent filter Element>

FeComposite(fs Filterspec, operator string, k1, k2, k3, k4 int, s ...string)

FeComposite specifies a feComposite filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feCompositeElement

FeConvolveMatrix(fs Filterspec, matrix [9]int, s ...string)

FeConvolveMatrix specifies a feConvolveMatrix filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feConvolveMatrixElement

 FeDiffuseLighting(fs Filterspec, scale, constant float64, s ...string) 

FeDiffuseLighting specifies a diffuse lighting filter primitive, a container for light source Element>s, end with DiffuseEnd()

 FeDiffEnd()

FeDiffuseEnd ends a diffuse lighting filter primitive container Standard reference: http://www.w3.org/TR/SVG11/filters.html#feDiffuseLightingElement

 FeDisplacementMap(fs Filterspec, scale float64, xchannel, ychannel string, s ...string)

FeDisplacementMap specifies a feDisplacementMap filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feDisplacementMapElement

 FeDistantLight(fs Filterspec, azimuth, elevation float64, s ...string)

FeDistantLight specifies a feDistantLight filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feDistantLightElement

 FeFlood(fs Filterspec, color string, opacity float64, s ...string)

FeFlood specifies a flood filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feFloodElement

FeFuncLinear(channel string, slope, intercept float64)

FeFuncLinear is the linear form of feFunc Standard reference: http://www.w3.org/TR/SVG11/filters.html#feComponentTransferElement

 FeFuncGamma(channel, amplitude, exponent, offset float64)

FeFuncGamma is the gamma curve form of feFunc Standard reference: http://www.w3.org/TR/SVG11/filters.html#feComponentTransferElement

FeFuncTable(channel string, tv []float64)

FeFuncGamma is the form of feFunc using a table of values Standard reference: http://www.w3.org/TR/SVG11/filters.html#feComponentTransferElement

FeFuncDiscrete(channel string, tv []float64)

FeFuncGamma is the form of feFunc using discrete values Standard reference: http://www.w3.org/TR/SVG11/filters.html#feComponentTransferElement

 FeGaussianBlur(fs Filterspec, stdx, stdy float64, s ...string)

FeGaussianBlur specifies a Gaussian Blur filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feGaussianBlurElement

 FeImage(href string, result string, s ...string)

FeImage specifies a feImage filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feImageElement

 FeMerge(nodes []string, s ...string)

FeMerge specifies a feMerge filter primitive, containing feMerge Element>s Standard reference: http://www.w3.org/TR/SVG11/filters.html#feMergeElement

 FeMorphology(fs Filterspec, operator string, xradius, yradius float64, s ...string)

FeMorphologyLight specifies a feMorphologyLight filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feMorphologyElement

 FeOffset(fs Filterspec, dx, dy int, s ...string)

FeOffset specifies the feOffset filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feOffsetElement

 FePointLight(x, y, z float64, s ...string)

FePointLight specifies a fePpointLight filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#fePointLightElement

 FeSpecularLighting(fs Filterspec, scale, constant float64, exponent int, color string, s ...string)

FeSpecularLighting specifies a specular lighting filter primitive, a container for light source elements, end with SpecularEnd()

 FeSpecEnd()

FeSpecularEnd ends a specular lighting filter primitive container Standard reference: http://www.w3.org/TR/SVG11/filters.html#feSpecularLightingElement

 FeSpotLight(fs Filterspec, x, y, z, px, py, pz float64, s ...string)

FeSpotLight specifies a feSpotLight filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feSpotLightElement

 FeTile(fs Filterspec, in string, s ...string)

FeTile specifies the tile utility filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feTileElement

 FeTurbulence(fs Filterspec, ftype string, bfx, bfy float64, octaves int, seed int64, stitch bool, s ...string)

FeTurbulence specifies a turbulence filter primitive Standard reference: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement

Filter convenience functions (modeled on CSS filter effects)

Blur(p float64)

Blur function by standard deviation

Brightness(p float64)

Brightness function (0-100)

Grayscale()

Apply a grayscale filter to the image

HueRotate(a float64)

Rotate Hues (0-360 degrees)

Invert()

Invert the image's colors

Saturate(p float64)

Percent saturation, 0 is grayscale

Sepia()

Apply sepia tone

Utility

Grid(x int, y int, w int, h int, n int, s ...string)

draws a grid of straight lines starting at x,y, with a width w, and height h, and a size of n.

Grid

Credits

Thanks to Jonathan Wright for the io.Writer update.

svgo's People

Contributors

ajstarks avatar krasin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

svgo's Issues

Pdf to SVG

I would like to implement this.

Can anyone offer any advice e on the mapping of pdf elements to SVG.

I read that inkscape supports this so it's definitely doable, and their are some strong pdf libraries for golang.

The use case is two fold.

  1. Take an existing pdf and load it into SVG play for editing.

  2. Save from SVG play as a pdf.

Support importing a svg into the SVG object

Would be really cool if we could get functionality that allowed us to take an already existing svg (a file, for example) and import it into svgo and modify it!

This would be really helpful when working with large preexisting svgs and adding dynamic content on top of it :)

Here how I envision it to be used:

buf, err := os.OpenFile("my.svg")
if err != nil {
  return err
}
canvas, err := svg.Import(buf, os.Stdout)
if err != nil {
  return err
}
canvas.DoAwesomeThings(...)
// ...
canvas.End() // my.svg with awesome things done to it printed to stdout

Really need two functions!!!

Really need two functions. Without them, library is not complete:

  1. Read the existing svg and the ability to add or modify it
  2. Calculation text width on font and font size. It need to inscribe text in rectangle, without departing from rectangle scope. Or split text to lines, without departing size of svg image

Be able to do these functions?

Grid of colors to svg

Hi,
As a kind of exercise, I've written some Go code that takes a grid of colors and produces simple xml for an svg of the same image.

Does your package include that functionality? If not, if I were to create a pull request, would you have time to evaluate it and decide whether to include it?

I could make a separate repo just for my code, but someone suggested I check with you first.

Thanks for your consideration.

Internal tools documentation, distribution, and features

Hi !
Great job, I really like the library.

How do you see space for eventual addition of documentation, features, and distribution channel to the internal tools ? They are distributed only though go, right ?

More practically I will be focused on svgrid, (neat!) which I will mostly use among the others, but I can foresee that I might need to:

  • extend it with some feature here and there
  • extend its command-line usage documentation
  • arrange a cross-platform distribution (win binary, linux via apt-get, brew on mac) and a CI.

These things might be, of course, done on the application side, but if you would be interested and they are something that you might merge, than I might design them to be generic, work directly on sigrid.go, and bring them upstream to the library, and other might use them.
With a CI and distribution setup done for svgrid, then of course, all the other tools might jump on the wagon as well.

Thank you in advance and thank you for sharing the library 👍

style tag

Hello. Is it possible to create such

  <style>
    text {
      fill: red;
    }
  </style>

tag via this library?
As far as I understood from the docs, there is no way to do it, so would PR with canvas.CSS(css string) implementation be merged?

Thanks in advance!

goplay removed in go1.3

The README mentions the use of the /misc/goplay utility, but it has been removed as of the go1.3 release.

Perhaps the README should be updated, or a local utility included to achieve the same effect.

Textlength attribute on Text

So far the package has been extremely useful, however I have run into my first issue:

e.g.

">x="75.0" y="-150.0" textLength="120.0" >Hello there</"

I don't see any way to set the Textlength attribute on text, this is not part of the style. Am I missing something?

Thank you.

Missing Translate with float parameters

In my pictures, I am seeing glitches which I think are due to the rounding of floating point numbers to ints because of the function Translate(x, y int). When nesting Scaling, Translation and Rotation operations, such rounding to ints will cause this effect. My workaround is to produce the transform(...) string myself.

No function for inserting <style type="text/css">

I believe there is a way to add the tag "style" into SVG like this <style type="text/css">...</script> However, I found only Script(string, string) function which can not be used for styling. I really don't know which function can be used for making style tag or it is really not there?

there is no support for embedding SVGs

It is not uncommon to want to embed SVG data inside an SVG.
For example, see this PR: https://github.com/juju/jujusvg/pull/8/files
In that PR, some SVGs have been produced by our design team,
and we want to use them as part of the higher level SVG generation.
We have manually translated them to svgo code, but that's obviously
not ideal. I've considered making a little parser to parse the SVG
and emit svgo calls, but that's not ideal - we're really just translating
one format to itself.

Perhaps a "RawSVG" call might work here - it could perhaps do some
XML processing (strip off the outer element) or perhaps just
write the exact bytes given.

Units Of Measure (UOM) and Precision

It is not clear to me what the units are for the 'x' and 'y' coordinates. I would like to work with millimeters and have better precision than a one millimeter. Since all the functions seem to take []int instead of []float it is not possible to get better than whole number precision.

Is there any way to solve this problem? Thx...

Dead link to SVGo Paper

I was curious to browse the paper, but the SVGo paper link in the repo is non-functional.

Could the link be updated and/or citation details added?

Add <title> to individual element?

Title seems like it will work fine for the whole canvas but for individual elements - seems it won't work based on reading the source. Is there any approach to take here?

Requesting support for tspan

Thanks for the useful library, one thing I found missing (and had to hack together myself) was support for tspan - as I was trying to center text with mixed styling.

This is what I ended up with in non-method form (the _svg functions are my replicas of the svgo private methods)

func startText(canvas *svg.SVG, x int, y int, s ...string) {
	_svg_printf(canvas, `<text %s %s`, _svg_loc(x, y), _svg_endstyle(s, ">"))
}

func addText(canvas *svg.SVG, t string, s ...string) {
	if len(s) == 0 {
		xml.Escape(canvas.Writer, []byte(t))
		return
	}
	_svg_printf(canvas, `<tspan %s`, _svg_endstyle(s, ">"))
	xml.Escape(canvas.Writer, []byte(t))
	_svg_printf(canvas, "</tspan>")
}

func endText(canvas *svg.SVG) {
	_svg_println(canvas, "</text>")
}

Potential code quality issues found

I forked this repo a while ago and ran a DeepSource analysis on it. DeepSource found a variety of different issues categorized based on their types and severity which you can view here.

Brief description -
Anti-Patterns: 148
Bug Risks: 9

You can find a detailed description and fixes for some of them here.

Please let me know what issues you'd like to focus on fixing and I'd be happy to take a look into it. Also, you can choose to hide certain types of issues too (if you wish to ignore them or you believe it is a false positive). I'd also be happy to send a patch with the DeepSource configuration file with the required fixes.

Pdf to SVG

I would like to implement this.

Can anyone offer any advice e on the mapping of pdf elements to SVG.

I read that inkscape supports this so it's definitely doable, and their are some strong pdf libraries for golang.

The use case is two fold.

  1. Take an existing pdf and load it into SVG play for editing.

  2. Save from SVG play as a pdf.

Help drawing a vertical text?

I am unsure whether to use transform=rotate(...), TextPath (only example I can find uses bezier which I don't need) or RotateTranslate? Tried searching around for issues/examples but nothing that cleared it up for me. Just trying to do something like this:

image

Including units and floating point values

Hey, thanks for making a neat package!

I might have missed this feature, but, have you considered support for floating point and specified unit types (eg. x=10.5cm) ?

Happy to do the refactor to replace the instances of int with a float/unit type if you'd be interested.

Cheers,

Ryan

Add method for rotation around the center

func (svg *SVG) RotateCenter(r float64, x, y int) { svg.Gtransform(rotateCenter(r, x, y)) }

func rotateCenter(r float64, x, y int) string { return fmt.Sprintf(rotate(%g %d %d), r, x, y) }

Please add LICENSE

Hi,

Please, consider adding a LICENSE to avoid ambiguity!

Thank you in advance!

Start method too strict for width and height parameters

One of the examples from http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_web shows a use of viewboxes to stretch the svg to whatever its container is sized as, with width and height set to a percentage:

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 200 200">
<circle r="50" cx="100" cy="100"/>
</svg>

I made a few modifications to svgo to support this kind of Start:

// Startraw begins the SVG document with the width w and height h.
// Other attributes may be optionally added, for example viewbox or additional namespaces
// Standard Reference: http://www.w3.org/TR/SVG11/struct.html#SVGElement
func (svg *SVG) Startraw(w, h string, attrs ...string) {
    svg.printf(svginit, w, h)
    for _, v := range attrs {
        svg.printf("\n     %s", v)
    }
    svg.println(svgns)
}

Which is nearly identical to Start, but takes strings. svginit's width and height format verbs are changed to %v to accommodate. I'm not sure if this is a good fit for svgo, but some may find it useful.

Text() attribute styling/spacing

There are issues with how Text() is generated, regarding both spacing and the use of style...at least when viewing in Chrome browser.

Examples:

canvas.Text(300, 150, "Some Text", "font-size:48px;", `fill="#222222"`)
<text x="300" y="150" style="font-size:48px;"fill="#222222" >Some Text</text>

canvas.Text(300, 150, "Some Text", "font-size:48px;", "fill:white")
<text x="300" y="150" style="font-size:48px;" style="fill:white">Some Text</text>

In the first example, you can see that the fill attribute has no spacing before it which in Chrome, produces an attributes construct error message. Also, there is an unnecessary space before the closing >.

In the second example (after manually inserting that space before style) I get an Attribute style redefined message.

This is fixed very easily in endstyle(), which would also benefit from a little refactoring.

Support embedded style

SVGo is nice, however, for my use, I cannot find support for embedded CSS.

The closest thing I can find is SVG.Script(), I guess we should have SVG.Style(), that add a CSS section inside a DEF section: supporting CSS is also part of SVG 1.1 spec.

can't compile, missing library

I try to compile, even removed the previous .a library, it still can not compile.

version: c84686f

$ git clone https://github.com/ajstarks/svgo.git /opt/go/src/pkg/github.com/ajstarks/svgo
$ make -j5
6g svg.go
6g -I. svgdef.go
6g -I. flower.go
6g -I. funnel.go
svgdef.go:6: import /opt/go/pkg/linux_amd64/github.com/ajstarks/svgo.a: object is [linux amd64 af52fabbb535 8107 default tip] expected [linux amd64 b295b8bda20b 8875 default tip]
make: *** [svgdef] Error 1

$rm /opt/go/pkg/linux_amd64/github.com/ajstarks/svgo.a

$make
6g svg.go
6g -I. svgdef.go
svgdef.go:6: can't find import: github.com/ajstarks/svgo

README.markdown typo

cd $GOPATH/github.com/ajstarks/svgo

should be

cd $GOPATH/src/github.com/ajstarks/svgo

rotate(deg, cx, cy)

Please add a new method. I don't see him. Example: Hello Moz!

---> rotate(45 50 50)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.