Documentation ¶
Overview ¶
Package ggweb is wrapper around gopherjs that makes it more convenient to work with for making games.
A few lines to help get started, assuming there is a canvas element in the page with ID "main-canvas".
func main() { ggweb.Init(onInit) } func onInit() { width, height := 100, 100 display := ggweb.NewSurfaceFromID("main-canvas") display.SetSize(width, height) display.StyleColor(ggweb.Fill, color.Black) display.DrawRect(ggweb.Fill, display.Rect()) }
Check out the examples directory for more detailed examples.
TODO
- Touch input
- Network
Index ¶
- Variables
- func ColorToCSS(c color.Color) string
- func Error(args ...interface{})
- func EventToKey(evt *js.Object) key.Key
- func Info(args ...interface{})
- func Init(onReady func())
- func LocalStorageGet(key string) (val string, ok bool)
- func LocalStorageRemove(key string)
- func LocalStorageSet(key, val string)
- func Log(args ...interface{})
- func ModKeys() map[key.Key]bool
- func MousePos() geo.Vec
- func MousePressed() map[int]bool
- func MouseRel() geo.Vec
- func PressedKeys() map[key.Key]bool
- func RegisterEvents(s *Surface)
- func SetMainLoop(loop MainLoop)
- func UnregisterEvents(s *Surface)
- func UnsetMainLoop()
- func Warn(args ...interface{})
- func WindowRect() geo.Rect
- type ColorStop
- type CompositeOp
- type Cursor
- type DrawType
- type Font
- type FontFamily
- type FontStyle
- type FontVariant
- type FontWeight
- type LineCap
- type LineJoin
- type LinearGradient
- type MainLoop
- type Path
- func (p *Path) AddPath(p2 *Path)
- func (p *Path) Arc(x, y, r, startRadians, endRadians float64, counterclockwise bool)
- func (p *Path) ArcTo(x1, y1, x2, y2, r float64)
- func (p *Path) BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y float64)
- func (p *Path) Close()
- func (p *Path) Copy() *Path
- func (p *Path) Ellipse(r geo.Rect, rotateRadians, startRadians, endRadians float64, ...)
- func (p *Path) LineTo(x, y float64)
- func (p *Path) MoveTo(x, y float64)
- func (p *Path) QuadraticCurveTo(cpx, cpy, x, y float64)
- func (p *Path) Rect(r geo.Rect)
- type Pattern
- type RadialGradient
- type RepeatType
- type Sound
- func (s *Sound) Ended() bool
- func (s *Sound) Length() time.Duration
- func (s *Sound) Loop() bool
- func (s *Sound) Pause()
- func (s *Sound) Paused() bool
- func (s *Sound) Play()
- func (s *Sound) PlayFromStart()
- func (s *Sound) Pos() time.Duration
- func (s *Sound) SetLoop(l bool)
- func (s *Sound) SetPos(pos time.Duration)
- func (s *Sound) SetVolume(v float64)
- func (s *Sound) Volume() float64
- type Surface
- func (s *Surface) Alpha() float64
- func (s *Surface) Blit(source *Surface, x, y float64)
- func (s *Surface) BlitArea(source *Surface, area geo.Rect, x, y float64)
- func (s *Surface) ClearRect(r geo.Rect)
- func (s *Surface) ClipPath(p *Path)
- func (s *Surface) Copy() *Surface
- func (s *Surface) Cursor() Cursor
- func (s *Surface) DrawArc(t DrawType, r geo.Rect, startRadians, endRadians float64, ...)
- func (s *Surface) DrawCircle(t DrawType, x, y, radius float64)
- func (s *Surface) DrawEllipse(t DrawType, r geo.Rect)
- func (s *Surface) DrawLine(x1, y1, x2, y2 float64)
- func (s *Surface) DrawPath(t DrawType, p *Path)
- func (s *Surface) DrawRect(t DrawType, r geo.Rect)
- func (s *Surface) DrawText(t DrawType, text string, x, y float64)
- func (s *Surface) PixelData(area geo.Rect) []color.RGBA
- func (s *Surface) Rect() geo.Rect
- func (s *Surface) ResetTransform()
- func (s *Surface) Restore()
- func (s *Surface) Rotate(radians float64)
- func (s *Surface) Save()
- func (s *Surface) Scale(x, y float64)
- func (s *Surface) SetAlpha(a float64)
- func (s *Surface) SetCompositeOp(op CompositeOp)
- func (s *Surface) SetCursor(c Cursor)
- func (s *Surface) SetFont(f *Font)
- func (s *Surface) SetLineCap(cap LineCap)
- func (s *Surface) SetLineJoin(join LineJoin)
- func (s *Surface) SetLineMiterLimit(miter float64)
- func (s *Surface) SetLineWidth(width float64)
- func (s *Surface) SetPixelData(data []color.RGBA, area geo.Rect)
- func (s *Surface) SetSize(w, h int)
- func (s *Surface) SetTextAlign(a TextAlign)
- func (s *Surface) SetTextBaseline(b TextBaseline)
- func (s *Surface) SetTransform(a, b, c, d, e, f float64)
- func (s *Surface) StyleColor(t DrawType, c color.Color)
- func (s *Surface) StyleLinearGradient(t DrawType, g LinearGradient)
- func (s *Surface) StylePattern(t DrawType, p Pattern)
- func (s *Surface) StyleRadialGradient(t DrawType, g RadialGradient)
- func (s *Surface) TextWidth(text string) float64
- func (s *Surface) Transform(a, b, c, d, e, f float64)
- func (s *Surface) Translate(x, y float64)
- type TextAlign
- type TextBaseline
Constants ¶
This section is empty.
Variables ¶
var DisableContextMenu bool
var PreventKeyDefault = map[key.Key]bool{}
PreventKeyDefault is a set of key that should have their default behavior prevented.
var PromptBeforeQuit string
PromptBeforeQuit will ask the user for confirmation before leaving the page if not an empty string. The browser may or may not use this string in its message to the user.
var Stats = struct { // LoopDuration is the amount of time that the last execution of the main loop took. LoopDuration time.Duration }{}
Stats holds various bits of information that one may find useful.
Functions ¶
func ColorToCSS ¶
ColorToCSS converts a color to a CSS formatted color string, e.g. "rgba(0, 0, 0, 0)"
func Error ¶
func Error(args ...interface{})
Error prints an error to the console. This won't work until ggweb is initialized.
func EventToKey ¶
EventToKey takes a js event and returns the key.Key described by the event. Note that this function will not work on IE or Edge because they do not define the "code" property.
func Info ¶
func Info(args ...interface{})
Info prints an info log to the console. This won't work until ggweb is initialized.
func Init ¶
func Init(onReady func())
Init sets up ggweb and waits for the page to load then calls the onReady function. Calling Init more than once will have no effect. Init takes care of setting up the events for window resizing, quiting, and key presses. These can be retrieved via the gogame/events package. Don't forget to call RegisterEvents for the surface you would like to receive the others event types.
func LocalStorageGet ¶
LocalStorageGet retrieves the value associated with the given key. If there is no value then ok will be false.
func LocalStorageRemove ¶
func LocalStorageRemove(key string)
LocalStorageRemove removes the given key (and it's value) from local storage.
func LocalStorageSet ¶
func LocalStorageSet(key, val string)
LocalStorageSet sets the given key's value to val.
func Log ¶
func Log(args ...interface{})
Log prints to the console. This won't work until ggweb is initialized.
func MousePressed ¶
MousePressed returns a map that contains all pressed mouse buttons mapping to true.
func PressedKeys ¶
PressedKeys returns a map that contoins all pressed keys mapping to true.
func RegisterEvents ¶
func RegisterEvents(s *Surface)
RegisterEvents sets up the surface to receive mouse events. Only one surface can accept events at a time, calling RegisterEvents on a multiple surfaces will unregister them on previous ones.
func SetMainLoop ¶
func SetMainLoop(loop MainLoop)
SetMainLoop sets the callback for the main game loop. The given function will be called at a regular interval.
func UnregisterEvents ¶
func UnregisterEvents(s *Surface)
UnregisterEvents causes the surface to stop receiving events.
func Warn ¶
func Warn(args ...interface{})
Warn prints a warning to the console. This won't work until ggweb is initialized.
func WindowRect ¶
WindowRect returns a rectangle that covers the entire inner window of the browser.
Types ¶
type ColorStop ¶
ColorStop is used for gradients to specify at which point it reaches a color. Position is from 0.0 to 1.0 and is its relative position in the gradient, 0.0 being the start and 1.0 being the end.
type CompositeOp ¶
type CompositeOp string
CompositeOp defines a type of compositing operation for controlling how to draw one surface to another.
const ( // SourceOver is the default behavior. It simply draws the new surface over the destination. SourceOver CompositeOp = "source-over" // SourceIn only draws where the surface overlap, everwhere else will be transparent. SourceIn CompositeOp = "source-in" // SourceOut only draws the new surface where it doesn't overlap with the destination.. SourceOut CompositeOp = "source-out" // SourceAtop only draws the new surface where it overlaps with the destination. SourceAtop CompositeOp = "source-atop" // DestinationOver draws the new surface behind the destination. DestinationOver CompositeOp = "destination-over" // DestinationIn keeps the destination content only where it overlaps with the new surface. DestinationIn CompositeOp = "destination-in" // DestinationOut keeps the destination content only where it doesn't overlap. DestinationOut CompositeOp = "destination-out" // DestinationAtop keeps the destination content only where it overlaps and the new surface // is drawn behind. DestinationAtop CompositeOp = "destination-atop" // Lighter determines the color value of overlaping pixels by adding the color values. Lighter CompositeOp = "lighter" // Copy makes the destination surface a copy of the source. Copy CompositeOp = "copy" // Xor makes pixels transparent where both surfaces overlap, everwhere else is drawn normal. Xor CompositeOp = "xor" // Multiply multiplies the values of the corresponding pixels of both surfaces. Multiply CompositeOp = "multiply" // Screen inverts, multiplies, and inverts again (opposite of Multiply) Screen CompositeOp = "screen" // Overlay is a combination of multiply and screen. Overlay CompositeOp = "overlay" // Darken retains the darkest pixels of both surfaces. Darken CompositeOp = "darken" // Lighten retains the lightest pixels of both surfaces. Lighten CompositeOp = "lighten" // ColorDodge divides the destination surfaces by the inverted source surface. ColorDodge CompositeOp = "color-dodge" // ColorBurn divides the inverted destination surface by the source surface and inverts the result. ColorBurn CompositeOp = "color-burn" // HardLight is like overlay but with the source and destination swapped. HardLight CompositeOp = "hard-light" // SoftLight is a softer version of HardLight SoftLight CompositeOp = "soft-light" // Difference subtracts on surface from the other, whichever gives a positive value. Difference CompositeOp = "difference" // Exclusion is like difference but with lower contrast. Exclusion CompositeOp = "exclusion" // Hue preserves the luma and chroma of the destination while adopting the hue of the source. Hue CompositeOp = "hue" // Saturation preserves the luma and hue of the destination while adopting the chroma of the source. Saturation CompositeOp = "saturation" // Color preserves the luma of the destination while adopting the hue and chroma of the source. Color CompositeOp = "color" // Luminosity preserves the hue and chroma of the bottom layer while adopting the luma of the source. Luminosity CompositeOp = "luminosity" )
type Cursor ¶
type Cursor string
Cursor is a style for the cursor. It can be any valid css value for the cursor property, most of which are predefined in this package.
const ( CursorDefault Cursor = "default" CursorNone Cursor = "none" CursorPointer Cursor = "pointer" CursorText Cursor = "text" CursorVerticalText Cursor = "vertical-text" CursorProgress Cursor = "progress" CusorWait Cursor = "wait" CursorAlias Cursor = "alias" CursorAllScroll Cursor = "all-scroll" CursorMove Cursor = "move" CursorCell Cursor = "cell" CursorCopy Cursor = "copy" CursorCrosshair Cursor = "crosshair" CursorNSResize Cursor = "ns-resize" CursorEWResize Cursor = "ew-resize" CursorNESWResize Cursor = "nesw-resize" CursorNWSEResize Cursor = "nwse-resize" CursorRowReszie Cursor = "row-resize" CursorColResize Cursor = "col-resize" CursorHelp Cursor = "help" CursorNoDrop Cursor = "no-drop" CursorNotAllowed Cursor = "not-allowed" )
type Font ¶
type Font struct { // Size is the Font's height in pixels Size float64 Family FontFamily Style FontStyle Variant FontVariant Weight FontWeight }
Font describes the style of text.
type FontFamily ¶
type FontFamily string
FontFamily is the overall appearence of the font. The predefined families are the generic ones, it is possible to define any valid css font-family though, e.g. FontFamily("courier new, monospace")
const ( // FontFamilySerif has strokes at the ends of the characters. FontFamilySerif FontFamily = "serif" // FontFamilySansSerif has plain endings. FontFamilySansSerif FontFamily = "sans-serif" // FontFamilyMonospace gives equal width to all characters. FontFamilyMonospace FontFamily = "monospace" // FontFamilyCursive gives the characters a somewhat handwritten look. FontFamilyCursive FontFamily = "cursive" // FontFamilyFantasy is bit of a decorative kind of font. FontFamilyFantasy FontFamily = "fantasy" )
type FontVariant ¶
type FontVariant string
FontVariant normal or caps.
const ( // FontVariantNormal is the default variant. FontVariantNormal FontVariant = "normal" // FontVariantSmallCaps makes the font all capital letters. FontVariantSmallCaps FontVariant = "small-caps" )
type FontWeight ¶
type FontWeight string
FontWeight normal or bold.
const ( // FontWeightNormal is the default weight. FontWeightNormal FontWeight = "normal" // FontWeightBold makes the font bold. FontWeightBold FontWeight = "bold" )
type LineCap ¶
type LineCap string
LineCap is a style of line cap.
const ( // LineCapButt draws a line with no ends. LineCapButt LineCap = "butt" // LineCapRound draws a line with rounded ends with radius equal to half its width. LineCapRound LineCap = "round" // LineCapSquare draws a line with the ends capped with a box that extends by an amount // equal to half the lines width. LineCapSquare LineCap = "square" )
type LineJoin ¶
type LineJoin string
LineJoin is the style for the point where two lines are connected.
const ( // LineJoinRound joins lines with rounded corners. LineJoinRound LineJoin = "round" // LineJoinBevel joins lines by filling in the triangular gap between them. LineJoinBevel LineJoin = "bevel" // LineJoinMiter joins lines by extending the edges until they meet. LineJoinMiter LineJoin = "miter" )
type LinearGradient ¶
LinearGradient smoothly transitions between multiple colors in the direction defined by two points.
type MainLoop ¶
MainLoop is a callback function that returns a time value that can be compared to previous calls to determine the elapsed time.
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path is equivalent to the Path2D object in js. It holds a reusable sequence of instructions for drawing a path. One should use NewPath or NewPathSVG to create it.
func (*Path) Arc ¶
Arc draws a circular arc with center (x, y) radius r. The angle are specified counterclockwise relative to the +x axis.
func (*Path) ArcTo ¶
ArcTo draws an arc tangent to the line between (x1, y1), (x2, y2) and connected to the previous point by a straight line.
func (*Path) BezierCurveTo ¶
BezierCurveTo adds a bezier curve to the path from the current point to (x, y) with control points (cp1x, cp1y) for the start and (cp2x, cp2y) for the end.
func (*Path) Close ¶
func (p *Path) Close()
Close draws a line to the start of the last continous line.
func (*Path) Ellipse ¶
func (p *Path) Ellipse(r geo.Rect, rotateRadians, startRadians, endRadians float64, counterclockwise bool)
Ellipse draws an ellipse with the given rectangle. The ellipse will be rotated counterclockwise by rotateRadians. Other parameters are the same as Arc.
func (*Path) LineTo ¶
LineTo moves to the point (x, y) and draws a line between the previous position and the new position.
func (*Path) QuadraticCurveTo ¶
QuadraticCurveTo adds a quadratic curve to the path from the current point to (x, y) with control point (cpx, cpy).
type Pattern ¶
type Pattern struct { Source *Surface Type RepeatType }
Pattern is an image that optionally repeats. The default Type is RepeatXY.
type RadialGradient ¶
RadialGradient smoothly transitions between multiple colors from one circle to another.
type RepeatType ¶
type RepeatType string
RepeatType describes how to repeat.
const ( // RepeatXY repeats in both horizontal and vertical directions. RepeatXY RepeatType = "repeat" // RepeatX repeats in the horizontal direction. RepeatX RepeatType = "repeat-x" // RepeatY repeats in the vertical direction. RepeatY RepeatType = "repeat-y" // NoRepeat doesn't repeat. NoRepeat RepeatType = "no-repeat" )
type Sound ¶
type Sound struct {
// contains filtered or unexported fields
}
Sound is a music or sound clip.
func (*Sound) Pause ¶
func (s *Sound) Pause()
Pause stops playing the sound. It may be played again from where it left off by calling Play.
func (*Sound) Play ¶
func (s *Sound) Play()
Play plays the sound from its current position. If the sound has ended, or you would like to play it from the beginning the use SetPos(0) to go back to the start or use PlayFromStart.
func (*Sound) PlayFromStart ¶
func (s *Sound) PlayFromStart()
PlayFromStart plays the sound from the beginning.
type Surface ¶
Surface is wrapper for a canvas and its context. Generally you'll want to use one of the NewSurface* functions to create create the Surface. If initializing manually keep in mind that Surface's functions assume Canvas and Ctx are valid. Most of Surface's functions deal with float64 for positioning but, unless otherwise stated, values are floored before drawing.
func LoadImage ¶
LoadImage loads the given image and returns it as a Surface. Important: This is a blocking call and so cannot be called in a js callback or main thread without wrapping it in a go routine.
func NewSurface ¶
NewSurface creates a new Surface with the given dimensions.
func NewSurfaceFromCanvas ¶
NewSurfaceFromCanvas creates a new Surface from the given canvas. It panics if given a nil or undefined canvas.
func NewSurfaceFromID ¶
NewSurfaceFromID creates a new Surface using the canvas with the given ID. It panics if no canvas with the given ID is found. Including the '#' is optional.
func (*Surface) Alpha ¶
Alpha returns the global alpha value for the surface. 0.0 is transparent and 1.0 is opaque.
func (*Surface) BlitArea ¶
BlitArea draws the sub-region of source defined by area to s with the top left corner at x, y.
func (*Surface) ClipPath ¶
ClipPath sets the clipping area of the surface to be within the path. Note that if one wishes to only temporarily set the clip area then Save must be called before ClipPath and Restore after the desired drawing operations, there is no other way to reset the clip area.
func (*Surface) Copy ¶
Copy returns a new surface equivalent to s in size and content. Context state is not copied.
func (*Surface) Cursor ¶
Cursor returns the current appearence of the cursor when it is over the Display.
func (*Surface) DrawArc ¶
func (s *Surface) DrawArc(t DrawType, r geo.Rect, startRadians, endRadians float64, counterclockwise bool)
DrawArc draws an arc on the surface, i.e. any slice of an ellipse. The angles are counterclockwise relative to the +x axis. The counterclockwise parameter is for the direction to draw in.
func (*Surface) DrawCircle ¶
DrawCircle draws a circle on the surface.
func (*Surface) DrawEllipse ¶
DrawEllipse draws an ellipse on the surface within the given rectangle.
func (*Surface) PixelData ¶
PixelData returns a flat array of colors for each pixel within the given area.
func (*Surface) ResetTransform ¶
func (s *Surface) ResetTransform()
ResetTransform resets the transformation to the identy matrix.
func (*Surface) Scale ¶
Scale changes the scale of the surface. 1.0 keeps the current size, smaller values shrink and larger grow.
func (*Surface) SetAlpha ¶
SetAlpha sets the global alpha value for the surface. 0.0 is transparent and 1.0 is opaque.
func (*Surface) SetCompositeOp ¶
func (s *Surface) SetCompositeOp(op CompositeOp)
SetCompositeOp sets the composite operation to use. Default is SourceOver.
func (*Surface) SetCursor ¶
SetCursor sets the appearence of the cursor when it is over this Display.
func (*Surface) SetLineCap ¶
SetLineCap sets the style for line end.
func (*Surface) SetLineJoin ¶
SetLineJoin sets the style for line corners.
func (*Surface) SetLineMiterLimit ¶
SetLineMiterLimit sets the maximum miter length.
func (*Surface) SetLineWidth ¶
SetLineWidth sets the width for lines.
func (*Surface) SetPixelData ¶
SetPixelData sets the pixels within the given area to the colors in data. The number of elemts of data should match area.Area().
func (*Surface) SetSize ¶
SetSize resizes the surface. Resizing the surface clears it's contents and context state.
func (*Surface) SetTextAlign ¶
SetTextAlign sets the horizontal alignment of text.
func (*Surface) SetTextBaseline ¶
func (s *Surface) SetTextBaseline(b TextBaseline)
SetTextBaseline sets the vertical alignment of text.
func (*Surface) SetTransform ¶
SetTransform resets the transformation matrix then applies the one given.
func (*Surface) StyleColor ¶
StyleColor sets the fill/stoke to a solid color.
func (*Surface) StyleLinearGradient ¶
func (s *Surface) StyleLinearGradient(t DrawType, g LinearGradient)
StyleLinearGradient sets the fill/stroke style to a linear gradient.
func (*Surface) StylePattern ¶
StylePattern sets the fill/stoke style to a pattern.
func (*Surface) StyleRadialGradient ¶
func (s *Surface) StyleRadialGradient(t DrawType, g RadialGradient)
StyleRadialGradient sets the fill/stroke style to a radial gradient.
type TextAlign ¶
type TextAlign string
TextAlign aligns the text horizontally.
const ( // TextAlignStart aligns text at the start of the line according to locale, it is the default. TextAlignStart TextAlign = "start" // TextAlignEnd aligns text at the end of the line according to locale. TextAlignEnd TextAlign = "end" // TextAlignLeft alignes text to the left. TextAlignLeft TextAlign = "left" // TextAlignRight alignes text to the right. TextAlignRight TextAlign = "right" // TextAlignCenter alignes text to the center. TextAlignCenter TextAlign = "center" )
type TextBaseline ¶
type TextBaseline string
TextBaseline aligns the text verically.
const ( // TextBaselineAlphabetic is the default. TextBaselineAlphabetic TextBaseline = "alphabetic" // TextBaselineTop puts the baseline at the top. TextBaselineTop TextBaseline = "top" // TextBaselineBottom puts the baseline at the bottom. TextBaselineBottom TextBaseline = "bottom" // TextBaselineHanging is the hanging baseline. TextBaselineHanging TextBaseline = "hanging" // TextBaselineMiddle puts the baseline in the middle. TextBaselineMiddle TextBaseline = "middle" // TextBaselineIdeographic is the bottom of the characters if they go beneath the alphabetic baseline. TextBaselineIdeographic TextBaseline = "ideographic" )