raster

package
v0.1.0-alpha.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package raster is a pure-Go software 2D rasterizer: anti-aliased path filling and stroking, gradients, patterns, compositing, blur, filters, text and a display-list painter (Paint) for internal/render. It is also the engine behind the HTML canvas 2D context.

Index

Constants

This section is empty.

Variables

View Source
var (
	Black       = Color{0, 0, 0, 1}
	Transparent = Color{}
)

Black is opaque black; Transparent is transparent black.

View Source
var (
	SnapMinOps    = 120 // lists shorter than this are cheap enough to repaint
	SnapStable    = 2   // consecutive updates that must share the prefix
	SnapMinShare  = 4   // the prefix must be at least 1/SnapMinShare of the list
	SnapExtendMin = 2   // a snapshot is moved forward when the stable prefix grows by more than this many ops
)

Snapshot tuning (variables so tests can force the snapshot path).

View Source
var Identity = Matrix{1, 0, 0, 1, 0, 0}

Identity is the identity transform.

View Source
var ParallelBands = true

ParallelBands lets Update repaint the damaged bands concurrently (a variable so tests and benchmarks can compare).

View Source
var SnapBuilt, SnapUsed, SnapExtended atomic.Int64

SnapBuilt and SnapUsed count surface snapshots made and repaints that started from one (tests check the snapshot path is exercised).

View Source
var StripeRows = 64

StripeRows is the least height of a stripe a tall band is cut into.

Functions

func ApplyFilters

func ApplyFilters(s *Surface, fl []Filter)

ApplyFilters runs a CSS filter list over s in place (s must already be padded for blur/shadow extents).

func OpName

func OpName(op CompositeOp) string

OpName is the canonical canvas name of op.

func Paint

func Paint(list []render.Op, width, height int, dpr float64, env PaintEnv) *image.RGBA

Paint executes a display list into a new RGBA image of round(width*dpr) x round(height*dpr) device pixels (width/height are CSS px; coordinates in ops are CSS px scaled by dpr). The result is premultiplied RGBA; with an opaque Background it is also opaque.

func PointInPath

func PointInPath(p *Path, m Matrix, x, y float64, rule FillRule) bool

PointInPath tests a point against path p mapped through m.

Types

type Band

type Band struct{ Y0, Y1, X0, X1 int }

Band is a range of device rows. Band is a range of device rows, and the columns [X0,X1) of them that were repainted (X1 == 0: the whole width, for bands made by Damage).

func Damage

func Damage(old, cur *ListInfo) (bands []Band, ok bool)

Damage returns the bands of device rows (full surface width) whose pixels can differ between a paint of the old list and one of the new list. ok is false when the lists are too different (or not comparable) for an incremental repaint to pay.

The damage is whole rows on purpose: the scan converter treats a shape that crosses the clip's left or right edge slightly differently from one that does not (the part outside is folded into the edge column), and a full paint shows that only at the real clip edges. Repainting complete rows keeps the horizontal clip identical to a full paint's; clipping vertically is exact.

type Brush

type Brush struct {
	Color    Color
	Gradient *GradientDef
	Pattern  *Pattern
}

Brush is a fill or stroke source.

type Canvas

type Canvas struct {
	Surf *Surface
	DPR  float64
	Env  PaintEnv
	Info *ListInfo
	// contains filtered or unexported fields
}

Canvas holds the pixels of the last paint and the analysis of its list.

It can also hold a snapshot of the surface as it was after the first snapN ops of the list (the part that rarely changes: backgrounds, the toolbar beneath the field being typed in). While the first snapN ops are unchanged, a repaint starts from the snapshot's rows instead of redrawing everything under the changed ops.

func NewCanvas

func NewCanvas(w, h int, dpr float64, env PaintEnv) *Canvas

NewCanvas allocates a transparent w x h device-pixel canvas.

func (*Canvas) Image

func (cv *Canvas) Image() *image.RGBA

Image views the canvas pixels (shared, premultiplied).

func (*Canvas) Matches

func (cv *Canvas) Matches(w, h int, dpr float64, env PaintEnv) bool

Matches reports whether the canvas was made for these parameters.

func (*Canvas) Paint

func (cv *Canvas) Paint(list []render.Op)

Paint repaints the whole canvas from list.

func (*Canvas) Update

func (cv *Canvas) Update(list []render.Op) (bands []Band, full bool)

Update brings the canvas to list. It returns the rows that were repainted (nil when nothing changed) and whether that was the whole canvas.

type Color

type Color struct{ R, G, B, A float64 }

Color is a non-premultiplied sRGB color with components in [0,1].

func ParseColor

func ParseColor(s string, cur Color) (Color, bool)

ParseColor parses any CSS color syntax. currentColor resolves to cur.

func RGBA8

func RGBA8(r, g, b, a uint8) Color

RGBA8 builds a color from 8-bit components.

func (Color) CSS

func (c Color) CSS() string

CSS formats the color the way canvas fillStyle getters do.

func (Color) Premul8

func (c Color) Premul8() (r, g, b, a uint8)

Premul8 returns premultiplied 8-bit components.

func (Color) WithAlpha

func (c Color) WithAlpha(a float64) Color

WithAlpha multiplies alpha.

type CompositeOp

type CompositeOp int

CompositeOp is a Porter-Duff operator or blend mode.

const (
	SourceOver CompositeOp = iota
	SourceIn
	SourceOut
	SourceAtop
	DestinationOver
	DestinationIn
	DestinationOut
	DestinationAtop
	Lighter
	Copy
	Xor
	Clear
	Multiply
	Screen
	Overlay
	Darken
	Lighten
	ColorDodge
	ColorBurn
	HardLight
	SoftLight
	Difference
	Exclusion
	Hue
	Saturation
	ColorBlend
	Luminosity
	Plus // alias of Lighter for CSS plus-lighter
)

func ParseOp

func ParseOp(s string) (CompositeOp, bool)

ParseOp maps a canvas globalCompositeOperation / CSS mix-blend-mode name.

type Context

type Context struct {
	// contains filtered or unexported fields
}

func NewContext

func NewContext(w, h int) *Context

NewContext creates a context drawing onto a new transparent w x h surface.

func NewContextSurface

func NewContextSurface(s *Surface) *Context

NewContextSurface draws onto an existing surface.

func (*Context) BeginLayer

func (c *Context) BeginLayer(bounds IRect, filters []Filter)

BeginLayer redirects drawing into a transparent offscreen group covering bounds (device space, padded for the filters). Clips active before the layer are applied when EndLayer composites it.

func (*Context) ClearRect

func (c *Context) ClearRect(x, y, w, h float64)

ClearRect makes a rectangle transparent (ignores shadows and compositing).

func (*Context) ClipBounds

func (c *Context) ClipBounds() IRect

ClipBounds returns the current clip's bounding rect.

func (*Context) ClipPath

func (c *Context) ClipPath(p *Path, rule FillRule)

ClipPath intersects the clip with p (user space).

func (*Context) ClipPathDevice

func (c *Context) ClipPathDevice(p *Path, rule FillRule)

ClipPathDevice intersects the clip with a device-space path.

func (*Context) ClipRect

func (c *Context) ClipRect(x, y, w, h float64)

ClipRect intersects the clip with a rectangle (user space).

func (*Context) ClipRoundRect

func (c *Context) ClipRoundRect(r Rect, rad [4][2]float64)

ClipRoundRect intersects the clip with a rounded rectangle.

func (*Context) Concat

func (c *Context) Concat(m Matrix)

func (*Context) DrawImage

func (c *Context) DrawImage(img *Surface, sx, sy, sw, sh, dx, dy, dw, dh float64)

DrawImage draws the source rectangle (sx,sy,sw,sh) of img into the destination rectangle (dx,dy,dw,dh) in user space, using the context's smoothing, alpha, shadow, filter, composite op and clip.

func (*Context) DrawSurface

func (c *Context) DrawSurface(s *Surface, op CompositeOp, alpha float64)

DrawSurface composites a whole surface at (x,y) device pixels using the current alpha, op and clip, ignoring the transform.

func (*Context) EndLayer

func (c *Context) EndLayer(opacity float64, op CompositeOp)

EndLayer composites the innermost layer back with opacity and blend op.

func (*Context) FillPaint

func (c *Context) FillPaint() Brush

func (*Context) FillPath

func (c *Context) FillPath(p *Path, rule FillRule)

FillPath fills p with the fill paint.

func (*Context) FillPathDevice

func (c *Context) FillPathDevice(p *Path, rule FillRule)

FillPathDevice fills a path already in device space.

func (*Context) FillPathShader

func (c *Context) FillPathShader(p *Path, rule FillRule, sh Shader)

FillPathShader fills p (user space) with an explicit shader.

func (*Context) FillRect

func (c *Context) FillRect(x, y, w, h float64)

FillRect fills a rectangle in user space.

func (*Context) FillRectShader

func (c *Context) FillRectShader(x, y, w, h float64, sh Shader)

FillRectShader fills a rectangle with an explicit shader.

func (*Context) FillText

func (c *Context) FillText(text string, x, y, maxWidth float64)

FillText draws filled text.

func (*Context) Font

func (c *Context) Font() FontSpec

Font returns the current font spec.

func (*Context) GetImageData

func (c *Context) GetImageData(x, y, w, h int) []uint8

GetImageData returns straight-alpha RGBA bytes for a device rect.

func (*Context) GlobalAlpha

func (c *Context) GlobalAlpha() float64

func (*Context) IsPointInPath

func (c *Context) IsPointInPath(p *Path, x, y float64, rule FillRule) bool

IsPointInPath reports whether the device-space point (x,y) is inside p (p in user space; transformed by the CTM).

func (*Context) IsPointInStroke

func (c *Context) IsPointInStroke(p *Path, x, y float64) bool

IsPointInStroke reports whether (x,y) in device space lies on the stroke of p.

func (*Context) LayerDepth

func (c *Context) LayerDepth() int

LayerDepth is the number of open layers.

func (*Context) MapFamilies

func (c *Context) MapFamilies(fn func(string) string)

MapFamilies rewrites the family names of the current font (web fonts: the owner of the context swaps declared names for their document scope).

func (*Context) MeasureText

func (c *Context) MeasureText(text string) TextMetrics

MeasureText measures text under the context's text state.

func (*Context) Op

func (c *Context) Op() CompositeOp

func (*Context) PutImageData

func (c *Context) PutImageData(data []uint8, w, h, dx, dy, dirtyX, dirtyY, dirtyW, dirtyH int)

PutImageData writes straight-alpha pixels (w x h) at (dx,dy) restricted to the dirty rectangle (relative to the image data), replacing destination pixels without compositing, clipping or transforms.

func (*Context) ResetState

func (c *Context) ResetState()

ResetState restores all drawing state to defaults (surface untouched).

func (*Context) Restore

func (c *Context) Restore()

Restore pops the drawing state.

func (*Context) Rotate

func (c *Context) Rotate(a float64)

func (*Context) Save

func (c *Context) Save()

Save pushes the drawing state.

func (*Context) SaveDepth

func (c *Context) SaveDepth() int

SaveDepth is the number of saved states.

func (*Context) Scale

func (c *Context) Scale(x, y float64)

func (*Context) SetBaseFontSize

func (c *Context) SetBaseFontSize(v float64)

func (*Context) SetDirection

func (c *Context) SetDirection(d string)

func (*Context) SetFill

func (c *Context) SetFill(p Brush)

func (*Context) SetFilters

func (c *Context) SetFilters(f []Filter)

func (*Context) SetFont

func (c *Context) SetFont(s string) bool

SetFont sets the font from a CSS shorthand; false if invalid.

func (*Context) SetFontKerning

func (c *Context) SetFontKerning(k string)

func (*Context) SetGlobalAlpha

func (c *Context) SetGlobalAlpha(a float64)

func (*Context) SetLetterSpacing

func (c *Context) SetLetterSpacing(v float64)

func (*Context) SetOp

func (c *Context) SetOp(op CompositeOp)

func (*Context) SetShadow

func (c *Context) SetShadow(col Color, blur, dx, dy float64)

SetShadow configures the drop shadow (blur is the canvas shadowBlur value).

func (*Context) SetSmoothing

func (c *Context) SetSmoothing(on bool, q Quality)

func (*Context) SetStroke

func (c *Context) SetStroke(p Brush)

func (*Context) SetStrokeStyle

func (c *Context) SetStrokeStyle(s StrokeStyle)

func (*Context) SetTextAlign

func (c *Context) SetTextAlign(a string)

SetTextOptions sets the remaining text attributes.

func (*Context) SetTextBaseline

func (c *Context) SetTextBaseline(b string)

func (*Context) SetTransform

func (c *Context) SetTransform(m Matrix)

func (*Context) SetTransformStash

func (c *Context) SetTransformStash()

SetTransformStash is a no-op hook kept for symmetry with layers.

func (*Context) SetWordSpacing

func (c *Context) SetWordSpacing(v float64)

func (*Context) StrokePaint

func (c *Context) StrokePaint() Brush

func (*Context) StrokePath

func (c *Context) StrokePath(p *Path)

StrokePath strokes p with the stroke paint and style.

func (*Context) StrokeRect

func (c *Context) StrokeRect(x, y, w, h float64)

StrokeRect strokes a rectangle outline.

func (*Context) StrokeStyle

func (c *Context) StrokeStyle() StrokeStyle

func (*Context) StrokeText

func (c *Context) StrokeText(text string, x, y, maxWidth float64)

StrokeText draws text outlines.

func (*Context) Surface

func (c *Context) Surface() *Surface

Surface returns the current target surface.

func (*Context) Transform

func (c *Context) Transform() Matrix

func (*Context) Translate

func (c *Context) Translate(x, y float64)

type DashParams

type DashParams struct {
	Intervals     []float32
	Phase         float32
	InitialLen    float32
	InitialIndex  int
	IntervalTotal float32
}

DashParams are the precomputed values of SkDashImpl: the intervals (an even count), the phase reduced into the interval length, the length of the first dash and its index.

func NewDashParams

func NewDashParams(intervals []float32, phase float32) (DashParams, bool)

NewDashParams is SkDashImpl's constructor with CalcDashParameters; ok is false for intervals Skia rejects (negative, odd count after doubling, zero sum, non-finite).

func (DashParams) DashPath

func (d DashParams) DashPath(src *Path, width float32, cap LineCap, resScale float32) (dst *Path, stroked, ok bool)

DashPath applies the dash effect to src for a stroke of the given width and cap (SkDashImpl::onFilterPath with no cull rect). It returns the dashed path and whether the stroke was already applied to it (SkDashPath's special-line case, which turns a butt-capped straight line into the dash rectangles and leaves the paint to fill them). ok is false when Skia leaves the path alone (nothing dashable, or more than a million dashes), in which case the caller strokes src as it is.

type FillRule

type FillRule int

FillRule selects how winding numbers map to coverage.

const (
	NonZero FillRule = iota
	EvenOdd
)

type Filter

type Filter struct {
	Name  string    // blur, brightness, contrast, grayscale, hue-rotate, invert, opacity, saturate, sepia, drop-shadow
	Args  []float64 // blur: [sigma px]; amounts: [fraction]; hue-rotate: [degrees]; drop-shadow: [dx dy blur]
	Color Color     // drop-shadow
}

Filter is one CSS filter function.

func ParseFilterList

func ParseFilterList(s string, cur Color) ([]Filter, bool)

ParseFilterList parses a CSS filter value ("blur(2px) brightness(1.2)"). Returns ok=false on syntax errors; "none" yields an empty list.

type FilterMode

type FilterMode int

FilterMode selects image sampling.

const (
	FilterNearest FilterMode = iota
	FilterBilinear
	FilterMipmap // bilinear within the nearest mip level
	FilterBicubic
)

type FontSpec

type FontSpec struct {
	Families  []string
	Size      float64
	Weight    int
	Italic    bool
	SmallCaps bool
	Stretch   string
}

FontSpec is a parsed CSS font.

func ParseFont

func ParseFont(s string, baseSize float64) (FontSpec, bool)

ParseFont parses a CSS font shorthand as accepted by canvas (system fonts and "inherit"-style globals are rejected). baseSize resolves em and %.

func (FontSpec) String

func (f FontSpec) String() string

String serialises the font like browsers do for ctx.font.

type Glyph

type Glyph struct {
	R    rune
	X    float64 // pen offset from run origin
	Face *font.Face
	GID  int // glyph id when it is not simply the glyph of R (ligatures)
}

Glyph is a positioned character.

type GradKind

type GradKind int

GradKind selects the gradient geometry.

const (
	LinearGrad GradKind = iota
	RadialGrad          // two-point conical
	ConicGrad
)

type GradStop

type GradStop struct {
	Pos   float64
	Color Color
}

GradStop is a color stop at Pos.

type GradientDef

type GradientDef struct {
	Kind   GradKind
	X0, Y0 float64 // linear start / radial start center / conic center
	R0     float64 // radial start radius / conic start angle (radians)
	X1, Y1 float64 // linear end / radial end center
	R1     float64
	Stops  []GradStop
	Repeat bool // repeating-*-gradient: t wraps
	Premul bool // interpolate premultiplied (CSS) instead of straight (canvas)
}

GradientDef describes a gradient in its own coordinate space.

type IRect

type IRect struct{ X0, Y0, X1, Y1 int }

IRect is an integer pixel rectangle [X0,X1) x [Y0,Y1).

func (IRect) Empty

func (r IRect) Empty() bool

func (IRect) H

func (r IRect) H() int

func (IRect) Intersect

func (r IRect) Intersect(o IRect) IRect

Intersect returns the overlap of two rects.

func (IRect) Union

func (r IRect) Union(o IRect) IRect

Union returns the bounding rect of both.

func (IRect) W

func (r IRect) W() int

type ImageShader

type ImageShader struct {
	Img *Surface

	RepX, RepY bool
	Filter     FilterMode
	Clamp      IRect // sampling window in image pixels (empty = whole image)
	EdgeClamp  bool  // replicate edges instead of transparent outside (drawImage)
	// contains filtered or unexported fields
}

ImageShader samples a surface through a transform.

func NewImageShader

func NewImageShader(img *Surface, m Matrix, repX, repY bool, f FilterMode, alpha float64) *ImageShader

NewImageShader samples img where m maps image pixel space to device space.

func (*ImageShader) SetClamp

func (s *ImageShader) SetClamp(r IRect)

SetClamp restricts sampling to a window of image pixels (srcRect semantics).

func (*ImageShader) ShadeRow

func (s *ImageShader) ShadeRow(x, y, n int, dst []uint8)

type LineCap

type LineCap int

Cap and join styles.

const (
	CapButt LineCap = iota
	CapRound
	CapSquare
)

type LineJoin

type LineJoin int

Cap and join styles.

const (
	JoinMiter LineJoin = iota
	JoinRound
	JoinBevel
)

type ListInfo

type ListInfo struct {
	OK     bool
	Key    []uint64     // content + context key per op
	Bounds []IRect      // device bounds (a group's bounds for push ops)
	Pair   []int32      // push -> matching pop index (and pop -> push), else -1
	Wide   []bool       // damage touching this op / group must grow to its bounds
	Desc   []string     // op type names (SWEEF_NARROW_DEBUG)
	Exact  []bool       // painting the op under a horizontal clip gives the same pixels as unclipped (see narrow)
	Corner []cornerSpan // like Exact, unless the clip edge cuts the curved ends of the op (see cornerZone)
	Pre    []uint64     // Pre[i] hashes Key[:i]: equal prefixes paint equal intermediate surfaces
	Surf   IRect
}

ListInfo is the analysis of one display list.

func Analyze

func Analyze(list []render.Op, w, h int, dpr float64) *ListInfo

Analyze builds the ListInfo of list for a w x h device-pixel surface.

type Mask

type Mask struct {
	B      IRect
	Stride int
	A      []uint8
}

Mask is an 8-bit coverage map over Bounds.

func BlurMask

func BlurMask(m *Mask, sigmaX, sigmaY float64, dx, dy int, clip IRect) *Mask

BlurMask returns a copy of m blurred by sigma and offset (dx,dy), expanded as needed and cropped to clip.

func FillMask

func FillMask(p *Path, m Matrix, rule FillRule, clip IRect) *Mask

FillMask rasterizes a path transformed by m.

func RasterizePolys

func RasterizePolys(sp []Subpath, rule FillRule, clip IRect) *Mask

RasterizePolys produces a coverage mask of the (implicitly closed) polylines, restricted to clip. Returns nil when nothing is covered.

func StrokeMask

func StrokeMask(p *Path, m Matrix, st StrokeStyle, clip IRect) *Mask

StrokeMask rasterizes the stroke of p (in path space) transformed by m.

func StrokeMaskFx

func StrokeMaskFx(p *Path, m Matrix, st StrokeStyle, clip IRect) (mask *Mask, ok bool)

StrokeMaskFx strokes p (user space) with Skia's stroker and fills the outline, transformed by m, with its analytic anti-aliasing. ok is false for styles it does not cover (dashes, hairlines thinner than a device pixel), where StrokeMask should be used instead.

func (*Mask) At

func (m *Mask) At(x, y int) uint8

At returns coverage at absolute pixel coordinates.

func (*Mask) Row

func (m *Mask) Row(y int) []uint8

Row returns the coverage row for absolute y (nil outside).

type Mat3

type Mat3 [9]float64

Mat3 is a homography acting on (x, y, 1), row-major.

type Matrix

type Matrix [6]float64

Matrix is an affine transform [a b c d e f]: x' = a*x + c*y + e, y' = b*x + d*y + f.

func Rotate

func Rotate(a float64) Matrix

Rotate returns a rotation matrix (radians, clockwise in y-down space).

func Scale

func Scale(x, y float64) Matrix

Scale returns a scale matrix.

func Translate

func Translate(x, y float64) Matrix

Translate returns a translation matrix.

func (Matrix) Apply

func (m Matrix) Apply(x, y float64) (float64, float64)

Apply transforms a point.

func (Matrix) ApplyPt

func (m Matrix) ApplyPt(p Pt) Pt

ApplyPt transforms a point.

func (Matrix) Det

func (m Matrix) Det() float64

Det is the determinant of the linear part.

func (Matrix) Invert

func (m Matrix) Invert() (Matrix, bool)

Invert returns the inverse; ok is false for singular matrices.

func (Matrix) IsAxisAligned

func (m Matrix) IsAxisAligned() bool

IsAxisAligned reports whether m maps axis-aligned rectangles to axis-aligned rectangles (no rotation/skew other than 90 degree turns).

func (Matrix) IsIdentity

func (m Matrix) IsIdentity() bool

IsIdentity reports whether m is the identity.

func (Matrix) MaxScale

func (m Matrix) MaxScale() float64

MaxScale is the largest singular value, an upper bound on stretching.

func (Matrix) Mul

func (m Matrix) Mul(n Matrix) Matrix

Mul returns m*n: the transform that applies n first, then m.

type PaintEnv

type PaintEnv struct {
	// Bitmap returns live pixels for a render.Bitmap op's node (may be nil).
	Bitmap func(n *html.Node) image.Image
	// Background is painted first; the zero value is transparent. Browsers
	// use opaque white for the page canvas.
	Background Color
}

PaintEnv supplies resources to Paint.

type Painter

type Painter struct {
	// contains filtered or unexported fields
}

Painter executes display lists incrementally.

func NewPainter

func NewPainter(w, h int, dpr float64, env PaintEnv) *Painter

NewPainter creates a painter over a new w x h device pixel surface.

func (*Painter) Run

func (p *Painter) Run(list []render.Op)

Run executes ops.

func (*Painter) RunRegion

func (p *Painter) RunRegion(list []render.Op, info *ListInfo, region IRect)

RunRegion executes the ops of list that can reach region (the painter's clip), skipping whole groups that cannot.

func (*Painter) RunRegionFrom

func (p *Painter) RunRegionFrom(list []render.Op, info *ListInfo, region IRect, start int)

RunRegionFrom is RunRegion for a surface that already shows the result of list[:start]: those ops are not run again, only the clips and transforms that are still open at start are re-established.

func (*Painter) Surface

func (p *Painter) Surface() *Surface

Surface returns the painter's target.

type Path

type Path struct {
	Cmds []byte    // 'M','L','Q','C','Z'
	Pts  []float64 // 2 per M/L, 4 per Q, 6 per C
	// contains filtered or unexported fields
}

Path is a sequence of subpaths made of lines, quadratic and cubic curves. Coordinates are in whatever space the caller chose.

func NewPath

func NewPath() *Path

NewPath returns an empty path.

func ParseSVGPath

func ParseSVGPath(d string) (*Path, bool)

ParseSVGPath parses an SVG path data string into p.

func (*Path) AddPath

func (p *Path) AddPath(o *Path, m Matrix)

AddPath appends o (transformed by m) to p.

func (*Path) Arc

func (p *Path) Arc(cx, cy, rx, ry, rot, a0, a1 float64, ccw bool)

Arc adds an elliptical arc (center, radii, rotation, angles in radians), preceded by a connecting line when the path has a current point.

func (*Path) Bounds

func (p *Path) Bounds() (Rect, bool)

Bounds returns the control-point bounding box.

func (*Path) Clone

func (p *Path) Clone() *Path

Clone copies the path.

func (*Path) Close

func (p *Path) Close()

Close closes the current subpath.

func (*Path) CubicTo

func (p *Path) CubicTo(c1x, c1y, c2x, c2y, x, y float64)

CubicTo adds a cubic curve.

func (*Path) Current

func (p *Path) Current() (Pt, bool)

Current returns the current point.

func (*Path) Ellipse

func (p *Path) Ellipse(cx, cy, rx, ry float64)

Ellipse adds a full ellipse as four cubics.

func (*Path) Empty

func (p *Path) Empty() bool

Empty reports whether the path has no segments.

func (*Path) Flatten

func (p *Path) Flatten(tol float64) []Subpath

Flatten converts the path to polylines. tol is the maximum deviation in the path's own units.

func (*Path) LineTo

func (p *Path) LineTo(x, y float64)

LineTo adds a line.

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float64)

MoveTo starts a new subpath.

func (*Path) QuadTo

func (p *Path) QuadTo(cx, cy, x, y float64)

QuadTo adds a quadratic curve.

func (*Path) Rect

func (p *Path) Rect(x, y, w, h float64)

Rect adds a closed rectangle.

func (*Path) RoundRect

func (p *Path) RoundRect(r Rect, rad [4][2]float64)

RoundRect adds a rounded rectangle with per-corner elliptical radii (top-left, top-right, bottom-right, bottom-left; each [rx, ry]).

func (*Path) Transform

func (p *Path) Transform(m Matrix) *Path

Transform returns the path with every point mapped through m.

type Pattern

type Pattern struct {
	Img        *Surface
	RepX, RepY bool
	M          Matrix
}

Pattern is a repeating image source; M maps pattern space to user space.

type Pt

type Pt struct{ X, Y float64 }

Pt is a 2D point.

type Quality

type Quality int

Quality is imageSmoothingQuality.

const (
	QualityLow Quality = iota
	QualityMedium
	QualityHigh
)

type Rect

type Rect struct{ X, Y, W, H float64 }

Rect is a float rectangle (x, y, w, h).

func (Rect) Bottom

func (r Rect) Bottom() float64

func (Rect) OutsetBounds

func (r Rect) OutsetBounds() IRect

OutsetBounds returns the integer rect that fully contains r.

func (Rect) Right

func (r Rect) Right() float64

type Shader

type Shader interface {
	// ShadeRow fills dst (len >= 4n) for pixels x..x+n-1 on row y.
	ShadeRow(x, y, n int, dst []uint8)
}

Shader produces premultiplied RGBA8 source pixels for device coordinates.

func NewGradientShader

func NewGradientShader(d GradientDef, m Matrix, alpha float64) Shader

NewGradientShader builds a shader; m maps gradient space to device space.

func Solid

func Solid(c Color) Shader

Solid returns a constant color shader.

type Shaped

type Shaped struct {
	Glyphs []Glyph
	Width  float64
	Fake   bool // synthetic bold
	Skew   bool // synthetic italic
	Size   float64
	Set    *faceSet
	Lum    uint8 // text color luminance, selects the coverage preblend table
}

Shaped is a laid-out run.

func Shape

func Shape(spec FontSpec, text string, letterSpacing, wordSpacing float64, kern bool) *Shaped

Shape lays text out with the font spec: pair kerning (when kern) and standard ligatures (when letterSpacing is zero, as in browsers) from the font's OpenType tables, shaped word by word like canvas text in Chromium.

func ShapeDir

func ShapeDir(spec FontSpec, text string, letterSpacing, wordSpacing float64, kern bool, rtl bool) *Shaped

ShapeDir is Shape for a paragraph whose base direction is rtl when set. Text containing right-to-left characters is reordered with the Unicode bidirectional algorithm and Arabic letters take their joined forms; the glyphs of the result are in visual order.

func (*Shaped) FontMetrics

func (s *Shaped) FontMetrics() (asc, desc float64)

FontMetrics returns the integer-rounded ascent/descent browsers report.

type StrokeStyle

type StrokeStyle struct {
	Width      float64
	Cap        LineCap
	Join       LineJoin
	MiterLimit float64
	Dash       []float64
	DashOffset float64
}

StrokeStyle describes a stroke in the path's own coordinate space.

type Subpath

type Subpath struct {
	P      []Pt
	Smooth []bool
	Closed bool
}

Subpath is a flattened polyline. Smooth[i] marks vertices that lie inside a curve (joins there are smooth regardless of the line-join setting).

func ApplyDash

func ApplyDash(sp []Subpath, dash []float64, offset float64) []Subpath

ApplyDash splits polylines into dashes.

func StrokePolys

func StrokePolys(sp []Subpath, st StrokeStyle, tol float64) []Subpath

StrokePolys converts polylines into fill polygons (to be rendered with the non-zero rule).

type Surface

type Surface struct {
	R      IRect
	Stride int // bytes per row
	Pix    []uint8
	// Opaque promises that every pixel has alpha 255 (set by whoever fills the surface, never inferred); it
	// lets DrawImage take the fast video path.
	Opaque bool
}

Surface is a premultiplied RGBA8 pixel buffer covering R in device space.

func FromImage

func FromImage(img image.Image) *Surface

FromImage converts any image to a premultiplied surface at the origin.

func FromRGBAOpaque

func FromRGBAOpaque(m *image.RGBA) *Surface

FromRGBAOpaque views an image.RGBA whose pixels are all opaque as a surface without copying them: the caller promises not to change the image while the surface is in use.

func NewSurface

func NewSurface(w, h int) *Surface

NewSurface allocates a transparent surface of size w x h at the origin.

func NewSurfaceRect

func NewSurfaceRect(r IRect) *Surface

NewSurfaceRect allocates a transparent surface covering r.

func RenderSVG

func RenderSVG(doc *render.SVGDoc, w, h int, color render.Color) *Surface

RenderSVG rasterizes an SVG scene into a new w x h surface (device pixels), mapping the root viewBox onto the whole surface. It is the entry point for canvas drawImage() of SVG images.

func (*Surface) Clear

func (s *Surface) Clear()

Clear zeroes the surface.

func (*Surface) Clone

func (s *Surface) Clone() *Surface

Clone copies the surface.

func (*Surface) ColorAt

func (s *Surface) ColorAt(x, y int) color.NRGBA

ColorAt returns the straight-alpha color at absolute pixel coordinates.

func (*Surface) H

func (s *Surface) H() int

func (*Surface) Image

func (s *Surface) Image() *image.RGBA

Image views the surface as an image.RGBA (premultiplied, bounds at origin 0,0 when the surface origin is 0,0).

func (*Surface) Row

func (s *Surface) Row(y, x0, x1 int) []uint8

Row returns the pixel bytes for absolute coords y, x in [x0,x1).

func (*Surface) SetNRGBA

func (s *Surface) SetNRGBA(src []uint8, w, h, dx, dy int)

SetNRGBA writes non-premultiplied pixels (src, w x h) at (dx, dy) replacing the destination.

func (*Surface) ToNRGBA

func (s *Surface) ToNRGBA() *image.NRGBA

ToNRGBA converts to non-premultiplied 8-bit.

func (*Surface) W

func (s *Surface) W() int

W and H are the pixel dimensions.

type TextMetrics

type TextMetrics struct {
	Width                          float64
	ActualLeft, ActualRight        float64
	ActualAscent, ActualDescent    float64
	FontAscent, FontDescent        float64
	EmAscent, EmDescent            float64
	Hanging, Alphabetic, Ideograph float64
}

TextMetrics mirrors the canvas TextMetrics members.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL