canvas

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: BSD-3-Clause Imports: 13 Imported by: 10

README

canvas

PkgGoDev Build Status Go Report Card

This Go module utilizes WebSockets to establish communication with a 2D canvas graphics context in a web browser, providing a portable way to create interactive 2D graphics from within a Go program.

The Go program (server) sends draw commands to the web browser (client) via WebSocket using a binary format. In return, the client sends keyboard, mouse, and touch events to the server.

This module does not rely on operating system-specific backends or Cgo bindings. It also does not utilize WebAssembly, which means the Go code runs on the server side, rather than in the browser. The client-server design enables the canvas to be displayed on a different machine over the network.

Examples

The example subdirectory contains a variety of demo programs.

Screenshots of examples

Usage

Drawing

The ListenAndServe function initializes the canvas server and takes the following arguments: the network address with the port number to bind to, a run function, and an options structure that configures various aspects such as the canvas size in pixels or a title for the browser tab.

The run function is called when a client connects to the server. This serves as the entry point for drawing.

package main

import (
	"image/color"
	"log"

	"github.com/fzipp/canvas"
)

func main() {
	err := canvas.ListenAndServe(":8080", run, &canvas.Options{
		Title:  "Example 1: Drawing",
		Width:  100,
		Height: 80,
	})
	if err != nil {
		log.Fatal(err)
	}
}

func run(ctx *canvas.Context) {
	ctx.SetFillStyle(color.RGBA{R: 200, A: 255})
	ctx.FillRect(10, 10, 50, 50)
	// ...
	ctx.Flush()
}

After starting the program, you can access the canvas by opening http://localhost:8080 in a web browser.

The server doesn't immediately send each drawing operation to the client but instead buffers them until the Flush method is called. The flush should occur once the image or an animation frame is complete; otherwise, nothing will be displayed.

Each client connection starts its own run function as a goroutine. Access to shared state between client connections must be synchronized. If you don't want to share state between connections, you should keep it local to the run function and pass the state to other functions called by the run function.

An animation loop

To create an animation, you can use a for loop within the run function. Inside this loop, observe the ctx.Events() channel for a canvas.CloseEvent to exit the loop when the connection is closed.

A useful pattern is to create a struct that holds the animation state and has both an update and a draw method:

package main

import (
	"log"
	"time"

	"github.com/fzipp/canvas"
)

func main() {
	err := canvas.ListenAndServe(":8080", run, &canvas.Options{
		Title:  "Example 2: Animation",
		Width:  800,
		Height: 600,
	})
	if err != nil {
		log.Fatal(err)
	}
}

func run(ctx *canvas.Context) {
	d := &demo{}
	for {
		select {
		case event := <-ctx.Events():
			if _, ok := event.(canvas.CloseEvent); ok {
				return
			}
		default:
			d.update()
			d.draw(ctx)
			ctx.Flush()
			time.Sleep(time.Second / 6)
		}
	}
}

type demo struct {
	// Animation state, for example:
	x, y int
	// ...
}

func (d *demo) update() {
	// Update animation state for the next frame
	// ...
}

func (d *demo) draw(ctx *canvas.Context) {
	// Draw the frame here, based on the animation state
	// ...
}
Keyboard, mouse and touch events

To handle keyboard, mouse, and touch events, you need to specify which events the client should observe and send to the server. This is achieved by passing an EnabledEvents option to the ListenAndServe function. Mouse move events typically generate more WebSocket communication than the others, so you may want to enable them only if necessary.

The ctx.Events() channel receives the observed events, and a type switch is used to determine the specific event type. A useful pattern involves creating a handle method for event handling:

package main

import (
	"log"

	"github.com/fzipp/canvas"
)

func main() {
	err := canvas.ListenAndServe(":8080", run, &canvas.Options{
		Title:  "Example 3: Events",
		Width:  800,
		Height: 600,
		EnabledEvents: []canvas.Event{
			canvas.MouseDownEvent{},
			canvas.MouseMoveEvent{},
			canvas.TouchStartEvent{},
			canvas.TouchMoveEvent{},
			canvas.KeyDownEvent{},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
}

func run(ctx *canvas.Context) {
	d := &demo{}
	for !d.quit {
		select {
		case event := <-ctx.Events():
			d.handle(event)
		default:
			d.update()
			d.draw(ctx)
			ctx.Flush()
		}
	}
}

type demo struct {
	quit bool
	// ...
}

func (d *demo) handle(event canvas.Event) {
	switch e := event.(type) {
	case canvas.CloseEvent:
		d.quit = true
	case canvas.MouseDownEvent:
		// ...
	case canvas.MouseMoveEvent:
		// ...
	case canvas.TouchStartEvent:
		// ...
   	case canvas.TouchMoveEvent:
		// ...
   	case canvas.KeyDownEvent:
		// ...
	}
}

func (d *demo) update() {
	// ...
}

func (d *demo) draw(ctx *canvas.Context) {
	// ...
}

Note that the canvas.CloseEvent does not have to be explicitly enabled. It is always enabled by default.

Alternatives

2D game engines:

License

This project is free and open source software licensed under the BSD 3-Clause License.

Documentation

Overview

Package canvas communicates with an HTML canvas in a web browser via WebSocket. The server program sends draw commands to the canvas and the canvas sends mouse and keyboard events to the server.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ListenAndServe

func ListenAndServe(addr string, run func(*Context), opts *Options) error

ListenAndServe listens on the TCP network address addr and serves an HTML page on "/" with a canvas that connects to the server via WebSockets on a "/draw" endpoint. It also serves a JavaScript file on "/canvas-websocket.js" that is used by the HTML page to provide this functionality.

The run function is called when a client canvas connects to the server. The Context parameter of the run function allows the server to send draw commands to the canvas and receive events from the canvas. Each instance of the run function runs on its own goroutine, so the run function should not access shared state without proper synchronization.

The options configure various aspects the canvas such as its size, which events to handle etc.

func ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, run func(*Context), opts *Options) error

ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS / WSS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

func NewServeMux

func NewServeMux(run func(*Context), opts *Options) *http.ServeMux

NewServeMux creates a http.ServeMux as used by ListenAndServe.

Types

type AuxClickEvent

type AuxClickEvent struct{ MouseEvent }

The AuxClickEvent is fired when a non-primary pointing device button (any mouse button other than the primary—usually leftmost—button) has been pressed and released both within the same element.

type ClickEvent

type ClickEvent struct{ MouseEvent }

The ClickEvent is fired when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the canvas.

type CloseEvent

type CloseEvent struct{}

The CloseEvent is fired when the WebSocket connection to the client is closed. It is not necessary to enable the CloseEvent with Options.EnabledEvents, it is always enabled. Animation loops should handle the CloseEvent to quit the loop.

type CompositeOperation

type CompositeOperation byte

CompositeOperation represents the type of compositing operation to apply when drawing new shapes.

For visual explanations of the composite operations see the MDN docs for CanvasRenderingContext2D.globalCompositeOperation.

const (
	// OpSourceOver draws new shapes on top of the existing canvas content.
	OpSourceOver CompositeOperation = iota
	// OpSourceIn draws the new shape only where both the new shape and the
	// destination canvas overlap. Everything else is made transparent.
	OpSourceIn
	// OpSourceOut draws the new shape where it doesn't overlap the existing
	// canvas content.
	OpSourceOut
	// OpSourceAtop draws the new shape only where it overlaps the existing
	// canvas content.
	OpSourceAtop
	// OpDestinationOver draws new shapes behind the existing canvas content.
	OpDestinationOver
	// OpDestinationIn keeps the existing canvas content where both the new
	// shape and existing canvas content overlap. Everything else is made
	// transparent.
	OpDestinationIn
	// OpDestinationOut keeps the existing content where it doesn't overlap
	// the new shape.
	OpDestinationOut
	// OpDestinationAtop keeps the existing canvas content only where it
	// overlaps the new shape. The new shape is drawn behind the canvas
	// content.
	OpDestinationAtop
	// OpLighter determines the color by adding color values where both shapes
	// overlap.
	OpLighter
	// OpCopy shows only the new shape.
	OpCopy
	// OpXOR makes shapes transparent where both overlap and draws them normal
	// everywhere else.
	OpXOR
	// OpMultiply multiplies the pixels of the top layer with the corresponding
	// pixels of the bottom layer. A darker picture is the result.
	OpMultiply
	// OpScreen inverts, multiplies, and inverts the pixels again.
	// A lighter picture is the result (opposite of multiply)
	OpScreen
	// OpOverlay is a combination of OpMultiply and OpScreen. Dark parts on the
	// base layer become darker, and light parts become lighter.
	OpOverlay
	// OpDarken retains the darkest pixels of both layers.
	OpDarken
	// OpLighten retains the lightest pixels of both layers.
	OpLighten
	// OpColorDodge divides the bottom layer by the inverted top layer.
	OpColorDodge
	// OpColorBurn divides the inverted bottom layer by the top layer, and
	// then inverts the result.
	OpColorBurn
	// OpHardLight is a combination of multiply and screen like overlay, but
	// with top and bottom layer swapped.
	OpHardLight
	// OpSoftLight is a softer version of hard-light. Pure black or white does
	// not result in pure black or white.
	OpSoftLight
	// OpDifference subtracts the bottom layer from the top layer or the other
	// way round to always get a positive value.
	OpDifference
	// OpExclusion is like OpDifference, but with lower contrast.
	OpExclusion
	// OpHue preserves the luma and chroma of the bottom layer, while adopting
	// the hue of the top layer.
	OpHue
	// OpSaturation preserves the luma and hue of the bottom layer, while
	// adopting the chroma of the top layer.
	OpSaturation
	// OpColor preserves the luma of the bottom layer, while adopting the hue
	// and chroma of the top layer.
	OpColor
	// OpLuminosity preserves the hue and chroma of the bottom layer, while
	// adopting the luma of the top layer.
	OpLuminosity
)

type Context

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

Context is the server-side drawing context for a client-side canvas. It buffers all drawing operations until the Flush method is called. The Flush method then sends the buffered operations to the client.

The Context for a client-server connection is obtained from the parameter of the run function that was passed to ListenAndServe, ListenAndServeTLS, or NewServeMux.

func (*Context) Arc

func (ctx *Context) Arc(x, y, radius, startAngle, endAngle float64, anticlockwise bool)

Arc adds a circular arc to the current sub-path.

It creates a circular arc centered at (x, y) with a radius of radius, which must be positive. The path starts at startAngle, ends at endAngle, and travels in the direction given by anticlockwise. The angles are in radians, measured from the positive x-axis.

func (*Context) ArcTo

func (ctx *Context) ArcTo(x1, y1, x2, y2, radius float64)

ArcTo adds a circular arc to the current sub-path, using the given control points and radius. The arc is automatically connected to the path's latest point with a straight line, if necessary for the specified parameters.

This method is commonly used for making rounded corners.

(x1, y1) are the coordinates of the first control point, (x2, y2) are the coordinates of the second control point. The radius must be non-negative.

Note: Be aware that you may get unexpected results when using a relatively large radius: the arc's connecting line will go in whatever direction it must to meet the specified radius.

func (*Context) BeginPath

func (ctx *Context) BeginPath()

BeginPath starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.

Note: To create a new sub-path, i.e., one matching the current canvas state, you can use MoveTo.

func (*Context) BezierCurveTo

func (ctx *Context) BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y float64)

BezierCurveTo adds a cubic Bézier curve to the current sub-path. It requires three points: the first two are control points and the third one is the end point. The starting point is the latest point in the current path, which can be changed using MoveTo before creating the Bézier curve.

(cp1x, cp1y) are the coordinates of the first control point, (cp2x, cp2y) the coordinates of the second control point, and (x, y) the coordinates of the end point.

func (*Context) CanvasHeight

func (ctx *Context) CanvasHeight() int

CanvasHeight returns the height of the canvas in pixels.

func (*Context) CanvasWidth

func (ctx *Context) CanvasWidth() int

CanvasWidth returns the width of the canvas in pixels.

func (*Context) ClearRect

func (ctx *Context) ClearRect(x, y, width, height float64)

ClearRect erases the pixels in a rectangular area by setting them to transparent black.

It sets the pixels in a rectangular area to transparent black (rgba(0,0,0,0)). The rectangle's corner is at (x, y), and its size is specified by width and height.

Note: Be aware that ClearRect may cause unintended side effects if you're not using paths properly. Make sure to call BeginPath before starting to draw new items after calling ClearRect.

func (*Context) Clip

func (ctx *Context) Clip()

Clip turns the current or given path into the current clipping region. The previous clipping region, if any, is intersected with the current or given path to create the new clipping region.

Note: Be aware that the clipping region is only constructed from shapes added to the path. It doesn't work with shape primitives drawn directly to the canvas, such as FillRect. Instead, you'd have to use Rect to add a rectangular shape to the path before calling Clip.

func (*Context) ClosePath

func (ctx *Context) ClosePath()

ClosePath attempts to add a straight line from the current point to the start of the current sub-path. If the shape has already been closed or has only one point, this function does nothing.

This method doesn't draw anything to the canvas directly. You can render the path using the Stroke or Fill methods.

func (*Context) CreateImageData

func (ctx *Context) CreateImageData(m image.Image) *ImageData

CreateImageData creates a new, blank ImageData object on the client with the specified dimensions. All of the pixels in the new object are transparent black. The ImageData object should be released with the ImageData.Release method when it is no longer needed.

func (*Context) CreateLinearGradient

func (ctx *Context) CreateLinearGradient(x0, y0, x1, y1 float64) *Gradient

CreateLinearGradient creates a gradient along the line connecting two given coordinates. To be applied to a shape, the gradient must first be set via the SetFillStyleGradient or SetStrokeStyleGradient methods.

(x0, y0) defines the start point, and (x1, y1) defines the end point of the gradient line.

Note: Gradient coordinates are global, i.e., relative to the current coordinate space. When applied to a shape, the coordinates are NOT relative to the shape's coordinates.

func (*Context) CreatePattern

func (ctx *Context) CreatePattern(src *ImageData, repetition PatternRepetition) *Pattern

CreatePattern creates a pattern using the specified image and repetition. The repetition indicates how to repeat the pattern's image.

This method doesn't draw anything to the canvas directly. The pattern it creates must be set via the SetFillStylePattern or SetStrokeStylePattern methods, after which it is applied to any subsequent drawing.

func (*Context) CreateRadialGradient

func (ctx *Context) CreateRadialGradient(x0, y0, r0, x1, y1, r1 float64) *Gradient

CreateRadialGradient creates a radial gradient using the size and coordinates of two circles. To be applied to a shape, the gradient must first be set via the SetFillStyleGradient or SetStrokeStyleGradient methods.

(x0, y0) defines the center, and r0 the radius of the start circle. (x1, y1) defines the center, and r1 the radius of the end circle. Each radius must be non-negative and finite.

Note: Gradient coordinates are global, i.e., relative to the current coordinate space. When applied to a shape, the coordinates are NOT relative to the shape's coordinates.

func (*Context) DrawImage

func (ctx *Context) DrawImage(src *ImageData, dx, dy float64)

DrawImage draws an image onto the canvas.

(dx, dy) is the position in the destination canvas at which to place the top-left corner of the source image.

func (*Context) DrawImageScaled

func (ctx *Context) DrawImageScaled(src *ImageData, dx, dy, dWidth, dHeight float64)

DrawImageScaled draws an image onto the canvas.

(dx, dy) is the position in the destination canvas at which to place the top-left corner of the source image; dWidth and dHeight are the width to draw the image in the destination canvas. This allows scaling of the drawn image.

func (*Context) DrawImageSubRectangle

func (ctx *Context) DrawImageSubRectangle(src *ImageData, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight float64)

DrawImageSubRectangle draws an image onto the canvas.

(sx, sy) is the position of the top left corner of the sub-rectangle of the source image to draw into the destination context; sWidth and sHeight are the width and height of the sub-rectangle of the source image to draw into the destination context.

(dx, dy) is the position in the destination canvas at which to place the top-left corner of the source image; dWidth and dHeight are the width to draw the image in the destination canvas. This allows scaling of the drawn image.

func (*Context) Ellipse

func (ctx *Context) Ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle float64, anticlockwise bool)

Ellipse adds an elliptical arc to the current sub-path.

It creates an elliptical arc centered at (x, y) with the radii radiusX and radiusY. The path starts at startAngle and ends at endAngle, and travels in the direction given by anticlockwise.

The radii must be non-negative. The rotation and the angles are expressed in radians. The angles are measured clockwise from the positive x-axis.

func (*Context) Events

func (ctx *Context) Events() <-chan Event

Events returns a channel of events sent by the client.

A type switch on the received Event values can differentiate between the concrete event types such as MouseDownEvent or KeyUpEvent.

func (*Context) Fill

func (ctx *Context) Fill()

Fill fills the current path with the current fill style (see SetFillStyle, SetFillStyleString, SetFillStyleGradient, SetFillStylePattern).

func (*Context) FillRect

func (ctx *Context) FillRect(x, y, width, height float64)

FillRect draws a rectangle that is filled according to the current fill style.

It draws a filled rectangle whose starting point is at (x, y) and whose size is specified by width and height. The fill style is determined by the current fill style (see SetFillStyle, SetFillStyleString, SetFillStyleGradient, SetFillStylePattern).

This method draws directly to the canvas without modifying the current path, so any subsequent Fill or Stroke calls will have no effect on it.

func (*Context) FillText

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

FillText draws a text string at the specified coordinates, filling the string's characters with the current fill style (see SetFillStyle, SetFillStyleString, SetFillStyleGradient, SetFillStylePattern).

This method draws directly to the canvas without modifying the current path, so any subsequent Fill or Stroke calls will have no effect on it.

The text is rendered using the font and text layout configuration as defined by the SetFont, SetTextAlign, and SetTextBaseline properties.

func (*Context) FillTextMaxWidth

func (ctx *Context) FillTextMaxWidth(text string, x, y, maxWidth float64)

FillTextMaxWidth draws a text string at the specified coordinates, filling the string's characters with the current fill style (see SetFillStyle, SetFillStyleString, SetFillStyleGradient, SetFillStylePattern).

The maxWidth parameter specifies the maximum number of pixels wide the text may be once rendered. The user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width.

This method draws directly to the canvas without modifying the current path, so any subsequent Fill or Stroke calls will have no effect on it.

The text is rendered using the font and text layout configuration as defined by the SetFont, SetTextAlign, and SetTextBaseline properties.

func (*Context) Flush

func (ctx *Context) Flush()

Flush sends the buffered drawing operations of the context from the server to the client.

Nothing is displayed on the client canvas until Flush is called. An animation loop usually has one flush per animation frame.

func (*Context) GetImageData

func (ctx *Context) GetImageData(sx, sy, sw, sh float64) *ImageData

GetImageData returns an ImageData object representing the underlying pixel data for a specified portion of the canvas.

(sx, sy) is the position of the top-left corner of the rectangle from which the ImageData will be extracted; sw and sh are the width and height of the rectangle from which the ImageData will be extracted.

This method is not affected by the canvas's transformation matrix. If the specified rectangle extends outside the bounds of the canvas, the pixels outside the canvas are transparent black in the returned ImageData object.

Note: Image data can be painted onto a canvas using the PutImageData method.

func (*Context) LineTo

func (ctx *Context) LineTo(x, y float64)

LineTo adds a straight line to the current sub-path by connecting the sub-path's last point to the specified (x, y) coordinates.

Like other methods that modify the current path, this method does not directly render anything. To draw the path onto a canvas, you can use the Fill or Stroke methods.

func (*Context) MoveTo

func (ctx *Context) MoveTo(x, y float64)

MoveTo begins a new sub-path at the point specified by the given (x, y) coordinates.

func (*Context) PutImageData

func (ctx *Context) PutImageData(src *ImageData, dx, dy float64)

PutImageData paints data from the given ImageData object onto the canvas. If a dirty rectangle is provided, only the pixels from that rectangle are painted. This method is not affected by the canvas transformation matrix.

(dx, dy) is the position at which to place the image data in the destination canvas.

Note: Image data can be retrieved from a canvas using the GetImageData method.

func (*Context) PutImageDataDirty

func (ctx *Context) PutImageDataDirty(src *ImageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight float64)

PutImageDataDirty paints data from the given ImageData object onto the canvas. If a dirty rectangle is provided, only the pixels from that rectangle are painted. This method is not affected by the canvas transformation matrix.

(dx, dy) is the position at which to place the image data in the destination canvas.

(dirtyX, dirtyY) is the position of the top-left corner from which the image data will be extracted; dirtyWidth and dirtyHeight are the width and height of the rectangle to be painted.

Note: Image data can be retrieved from a canvas using the GetImageData method.

func (*Context) QuadraticCurveTo

func (ctx *Context) QuadraticCurveTo(cpx, cpy, x, y float64)

QuadraticCurveTo adds a quadratic Bézier curve to the current sub-path. It requires two points: the first one is a control point and the second one is the end point. The starting point is the latest point in the current path, which can be changed using MoveTo before creating the quadratic Bézier curve.

(cpx, cpy) is the coordinate of the control point, and (x, y) is the coordinate of the end point.

func (*Context) Rect

func (ctx *Context) Rect(x, y, width, height float64)

Rect adds a rectangle to the current path.

It creates a rectangular path whose starting point is at (x, y) and whose size is specified by width and height. Like other methods that modify the current path, this method does not directly render anything. To draw the rectangle onto a canvas, you can use the Fill or Stroke methods.

Note: To both create and render a rectangle in one step, use the FillRect or StrokeRect methods.

func (*Context) Restore

func (ctx *Context) Restore()

Restore restores the most recently saved canvas state by popping the top entry in the drawing state stack. If there is no saved state, this method does nothing.

For more information about the drawing state, see Save.

func (*Context) Rotate

func (ctx *Context) Rotate(angle float64)

Rotate adds a rotation to the transformation matrix.

The rotation angle is expressed in radians (clockwise). You can use degree * math.Pi / 180 to calculate a radian from a degree.

The rotation center point is always the canvas origin. To change the center point, you will need to move the canvas by using the Translate method.

func (*Context) Save

func (ctx *Context) Save()

Save saves the entire state of the canvas by pushing the current state onto a stack.

The drawing state that gets saved onto a stack consists of:

  • The current transformation matrix.
  • The current clipping region.
  • The current dash list.
  • The current values of the attributes set via the following methods: SetStrokeStyle*, SetFillStyle*, SetGlobalAlpha, SetLineWidth, SetLineCap, SetLineJoin, SetMiterLimit, SetLineDashOffset, SetShadowOffsetX, SetShadowOffsetY, SetShadowBlur, SetShadowColor*, SetGlobalCompositeOperation, SetFont, SetTextAlign, SetTextBaseline, SetImageSmoothingEnabled.

func (*Context) Scale

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

Scale adds a scaling transformation to the canvas units horizontally and/or vertically.

By default, one unit on the canvas is exactly one pixel. A scaling transformation modifies this behavior. For instance, a scaling factor of 0.5 results in a unit size of 0.5 pixels; shapes are thus drawn at half the normal size. Similarly, a scaling factor of 2.0 increases the unit size so that one unit becomes two pixels; shapes are thus drawn at twice the normal size.

x is the scaling factor in the horizontal direction. A negative value flips pixels across the vertical axis. A value of 1 results in no horizontal scaling.

y is the scaling factor in the vertical direction. A negative value flips pixels across the horizontal axis. A value of 1 results in no vertical scaling.

func (*Context) SetFillStyle

func (ctx *Context) SetFillStyle(c color.Color)

SetFillStyle sets the color to use inside shapes. The default color is black.

func (*Context) SetFillStyleGradient

func (ctx *Context) SetFillStyleGradient(g *Gradient)

SetFillStyleGradient sets the gradient (a linear or radial gradient) to use inside shapes.

func (*Context) SetFillStylePattern

func (ctx *Context) SetFillStylePattern(p *Pattern)

SetFillStylePattern sets the pattern (a repeating image) to use inside shapes.

func (*Context) SetFillStyleString

func (ctx *Context) SetFillStyleString(color string)

SetFillStyleString sets the color to use inside shapes. The color is parsed as a CSS color value like "#a100cb", "#ccc", "darkgreen", "rgba(0.5, 0.2, 0.7, 1.0)", etc. The default color is "#000" (black).

func (*Context) SetFont

func (ctx *Context) SetFont(font string)

SetFont sets the current text style to use when drawing text. This string uses the same syntax as the CSS font specifier. The default font is "10px sans-serif".

func (*Context) SetGlobalAlpha

func (ctx *Context) SetGlobalAlpha(alpha float64)

SetGlobalAlpha sets the alpha (transparency) value that is applied to shapes and images before they are drawn onto the canvas. The alpha value is a number between 0.0 (fully transparent) and 1.0 (fully opaque), inclusive. The default value is 1.0. Values outside that range, including ±Inf and NaN, will not be set.

func (*Context) SetGlobalCompositeOperation

func (ctx *Context) SetGlobalCompositeOperation(mode CompositeOperation)

SetGlobalCompositeOperation sets the type of compositing operation to apply when drawing new shapes.

The default mode is OpSourceOver.

func (*Context) SetImageSmoothingEnabled

func (ctx *Context) SetImageSmoothingEnabled(enabled bool)

SetImageSmoothingEnabled determines whether scaled images are smoothed (true, default) or not (false).

This property is useful for games and other apps that use pixel art. When enlarging images, the default resizing algorithm will blur the pixels. Set this property to false to retain the pixels' sharpness.

func (*Context) SetLineCap

func (ctx *Context) SetLineCap(cap LineCap)

SetLineCap sets the shape used to draw the end points of lines. The default value is CapButt.

Note: Lines can be drawn with the Stroke, StrokeRect, and StrokeText methods.

func (*Context) SetLineDash

func (ctx *Context) SetLineDash(segments []float64)

SetLineDash sets the line dash pattern used when stroking lines. It uses a slice of values that specify alternating lengths of lines and gaps which describe the pattern.

The segments are a slice of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number of elements in the slice is odd, the elements of the slice get copied and concatenated. For example, {5, 15, 25} will become {5, 15, 25, 5, 15, 25}. If the slice is empty, the line dash list is cleared and line strokes return to being solid.

func (*Context) SetLineDashOffset

func (ctx *Context) SetLineDashOffset(offset float64)

SetLineDashOffset sets the line dash offset, or "phase." The default value is 0.0.

Note: Lines are drawn by calling the Stroke method.

func (*Context) SetLineJoin

func (ctx *Context) SetLineJoin(join LineJoin)

SetLineJoin sets the shape used to join two line segments where they meet. The default is JoinMiter.

This property has no effect wherever two connected segments have the same direction, because no joining area will be added in this case. Degenerate segments with a length of zero (i.e., with all endpoints and control points at the exact same position) are also ignored.

Note: Lines can be drawn with the Stroke, StrokeRect, and StrokeText methods.

func (*Context) SetLineWidth

func (ctx *Context) SetLineWidth(width float64)

SetLineWidth sets the thickness of lines. The width is a number in coordinate space units. Zero, negative, ±Inf, and NaN values are ignored. This value is 1.0 by default.

Note: Lines can be drawn with the Stroke, StrokeRect, and StrokeText methods.

func (*Context) SetMiterLimit

func (ctx *Context) SetMiterLimit(value float64)

SetMiterLimit sets the miter limit ratio. The miter limit ratio is a number in coordinate space units. Zero, negative, ±Inf, and NaN values are ignored. The default value is 10.0.

func (*Context) SetShadowBlur

func (ctx *Context) SetShadowBlur(level float64)

SetShadowBlur sets the amount of blur applied to shadows. The default is 0 (no blur).

The blur level is a non-negative float specifying the level of shadow blur, where 0 represents no blur and larger numbers represent increasingly more blur. This value doesn't correspond to a number of pixels, and is not affected by the current transformation matrix. Negative, ±Inf, and NaN values are ignored.

Note: Shadows are only drawn if the SetShadowColor / SetShadowColorString property is set to a non-transparent value. One of the SetShadowBlur, SetShadowOffsetX, or SetShadowOffsetY properties must be non-zero, as well.

func (*Context) SetShadowColor

func (ctx *Context) SetShadowColor(c color.Color)

SetShadowColor sets the color of shadows. The default value is fully-transparent black.

Be aware that the shadow's rendered opacity will be affected by the opacity of the SetFillStyle color when filling, and of the SetStrokeStyle color when stroking.

Note: Shadows are only drawn if the SetShadowColor / SetShadowColorString property is set to a non-transparent value. One of the SetShadowBlur, SetShadowOffsetX, or SetShadowOffsetY properties must be non-zero, as well.

func (*Context) SetShadowColorString

func (ctx *Context) SetShadowColorString(color string)

SetShadowColorString sets the color of shadows. The default value is fully-transparent black.

The color is parsed as a CSS color value like "#a100cb", "#ccc", "darkgreen", "rgba(0.5, 0.2, 0.7, 1.0)", etc.

Be aware that the shadow's rendered opacity will be affected by the opacity of the SetFillStyle color when filling, and of the SetStrokeStyle color when stroking.

Note: Shadows are only drawn if the SetShadowColor / SetShadowColorString property is set to a non-transparent value. One of the SetShadowBlur, SetShadowOffsetX, or SetShadowOffsetY properties must be non-zero, as well.

func (*Context) SetShadowOffsetX

func (ctx *Context) SetShadowOffsetX(offset float64)

SetShadowOffsetX sets the distance that shadows will be offset horizontally.

The offset is a float specifying the distance that shadows will be offset horizontally. Positive values are to the right, and negative to the left. The default value is 0 (no horizontal offset). ±Inf and NaN values are ignored.

Note: Shadows are only drawn if the SetShadowColor / SetShadowColorString property is set to a non-transparent value. One of the SetShadowBlur, SetShadowOffsetX, or SetShadowOffsetY properties must be non-zero, as well.

func (*Context) SetShadowOffsetY

func (ctx *Context) SetShadowOffsetY(offset float64)

SetShadowOffsetY sets the distance that shadows will be offset vertically.

The offset is a float specifying the distance that shadows will be offset vertically. Positive values are down, and negative are up. The default value is 0 (no vertical offset). ±Inf and NaN values are ignored.

Note: Shadows are only drawn if the SetShadowColor / SetShadowColorString property is set to a non-transparent value. One of the SetShadowBlur, SetShadowOffsetX, or SetShadowOffsetY properties must be non-zero, as well.

func (*Context) SetStrokeStyle

func (ctx *Context) SetStrokeStyle(c color.Color)

SetStrokeStyle sets the color to use for the strokes (outlines) around shapes. The default color is black.

The color is parsed as a CSS color value like "#a100cb", "#ccc", "darkgreen", "rgba(0.5, 0.2, 0.7, 1.0)", etc.

func (*Context) SetStrokeStyleGradient

func (ctx *Context) SetStrokeStyleGradient(g *Gradient)

SetStrokeStyleGradient sets the gradient (a linear or radial gradient) to use for the strokes (outlines) around shapes.

func (*Context) SetStrokeStylePattern

func (ctx *Context) SetStrokeStylePattern(p *Pattern)

SetStrokeStylePattern sets the pattern (a repeating image) to use for the strokes (outlines) around shapes.

func (*Context) SetStrokeStyleString

func (ctx *Context) SetStrokeStyleString(color string)

SetStrokeStyleString sets the color to use for the strokes (outlines) around shapes. The default color is black.

func (*Context) SetTextAlign

func (ctx *Context) SetTextAlign(align TextAlign)

SetTextAlign sets the current text alignment used when drawing text.

The alignment is relative to the x value of the FillText method. For example, if the text alignment is set to AlignCenter, then the text's left edge will be at x - (textWidth / 2).

The default value is AlignStart.

func (*Context) SetTextBaseline

func (ctx *Context) SetTextBaseline(baseline TextBaseline)

SetTextBaseline sets the current text baseline used when drawing text.

The default value is BaselineAlphabetic.

func (*Context) SetTransform

func (ctx *Context) SetTransform(a, b, c, d, e, f float64)

SetTransform resets (overrides) the current transformation to the identity matrix, and then invokes a transformation described by the arguments of this method. This lets you scale, rotate, translate (move), and skew the context. The transformation matrix is described by:

[ a b 0 ]
[ c d 0 ]
[ e f 1 ]

a: Horizontal scaling. A value of 1 results in no scaling.
b: Vertical skewing.
c: Horizontal skewing.
d: Vertical scaling. A value of 1 results in no scaling.
e: Horizontal translation (moving).
f: Vertical translation (moving).

Note: See also the Transform method; instead of overriding the current transform matrix, it multiplies it with a given one.

func (*Context) Stroke

func (ctx *Context) Stroke()

Stroke outlines the current or given path with the current stroke style.

Strokes are aligned to the center of a path; in other words, half of the stroke is drawn on the inner side, and half on the outer side.

The stroke is drawn using the non-zero winding rule, which means that path intersections will still get filled.

func (*Context) StrokeRect

func (ctx *Context) StrokeRect(x, y, width, height float64)

StrokeRect draws a rectangle that is stroked (outlined) according to the current stroke style and other context settings.

It draws a stroked rectangle whose starting point is at (x, y) and whose size is specified by width and height.

This method draws directly to the canvas without modifying the current path so any subsequent Fill or Stroke calls will have no effect on it.

func (*Context) StrokeText

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

StrokeText strokes - that is, draws the outlines of - the characters of a text string at the specified coordinates.

The text is rendered using the settings specified by SetFont, SetTextAlign, and SetTextBaseline. (x, y) is the coordinate of the point at which to begin drawing the text.

This method draws directly to the canvas without modifying the current path, so any subsequent Fill or Stroke calls will have no effect on it.

Use the FillText method to fill the text characters rather than having just their outlines drawn.

func (*Context) StrokeTextMaxWidth

func (ctx *Context) StrokeTextMaxWidth(text string, x, y, maxWidth float64)

StrokeTextMaxWidth strokes - that is, draws the outlines of - the characters of a text string at the specified coordinates. A parameter allows specifying a maximum width for the rendered text, which the user agent will achieve by condensing the text or by using a lower font size.

The text is rendered using the settings specified by SetFont, SetTextAlign, and SetTextBaseline. (x, y) is the coordinate of the point at which to begin drawing the text.

The user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified maxWidth.

This method draws directly to the canvas without modifying the current path, so any subsequent Fill or Stroke calls will have no effect on it.

Use the FillText method to fill the text characters rather than having just their outlines drawn.

func (*Context) Transform

func (ctx *Context) Transform(a, b, c, d, e, f float64)

Transform multiplies the current transformation with the matrix described by the arguments of this method. This lets you scale, rotate, translate (move), and skew the context. The transformation matrix is described by:

[ a b 0 ]
[ c d 0 ]
[ e f 1 ]

a: Horizontal scaling. A value of 1 results in no scaling.
b: Vertical skewing.
c: Horizontal skewing.
d: Vertical scaling. A value of 1 results in no scaling.
e: Horizontal translation (moving).
f: Vertical translation (moving).

Note: See also the SetTransform method, which resets the current transform to the identity matrix and then invokes Transform.

func (*Context) Translate

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

Translate adds a translation transformation to the current matrix by moving the canvas and its origin x units horizontally and y units vertically on the grid.

Positive x values are to the right, and negative to the left. Positive y values are down, and negative are up.

type DblClickEvent

type DblClickEvent struct{ MouseEvent }

The DblClickEvent is fired when a pointing device button (such as a mouse's primary button) is double-clicked; that is, when it's rapidly clicked twice on the canvas within a very short span of time.

DblClickEvent fires after two ClickEvents (and by extension, after two pairs of MouseDownEvents and MouseUpEvents).

type DeltaMode

type DeltaMode byte

DeltaMode represents the unit of the delta values' scroll amount.

const (
	// DeltaPixel means the delta values are specified in pixels.
	DeltaPixel DeltaMode = iota
	// DeltaLine means the delta values are specified in lines.
	DeltaLine
	// DeltaPage means the delta values are specified in pages.
	DeltaPage
)

type Event

type Event interface {
	// contains filtered or unexported methods
}

Event is an interface implemented by all event subtypes. Events can be received from the channel returned by Context.Events. Use a type switch to distinguish between different event types.

type Gradient

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

Gradient represents a gradient. It is returned by the methods Context.CreateLinearGradient and Context.CreateRadialGradient. It can be used with the Context.SetFillStyleGradient and Context.SetStrokeStyleGradient methods.

The gradient should be released with the Release method when it is no longer needed.

func (*Gradient) AddColorStop

func (g *Gradient) AddColorStop(offset float64, c color.Color)

AddColorStop adds a new stop, defined by an offset and a color, to the gradient.

func (*Gradient) AddColorStopString

func (g *Gradient) AddColorStopString(offset float64, color string)

AddColorStopString adds a new stop, defined by an offset and a color, to the gradient.

The color is parsed as a CSS color value like "#a100cb", "#ccc", "darkgreen", "rgba(0.5, 0.2, 0.7, 1.0)", etc.

func (*Gradient) Release

func (g *Gradient) Release()

Release releases the gradient on the client side.

type ImageData

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

ImageData represents the underlying pixel data of an image. It is created using the Context.CreateImageData and Context.GetImageData methods. It can also be used to set a part of the canvas by using Context.PutImageData, Context.PutImageDataDirty, Context.DrawImage and Context.DrawImageScaled.

The image data should be released with the Release method when it is no longer needed.

func (*ImageData) Height

func (m *ImageData) Height() int

Height returns the actual height, in pixels, of the image.

func (*ImageData) Release

func (m *ImageData) Release()

Release releases the image data on the client side.

func (*ImageData) Width

func (m *ImageData) Width() int

Width returns the actual width, in pixels, of the image.

type KeyDownEvent

type KeyDownEvent struct{ KeyboardEvent }

The KeyDownEvent is fired when a key is pressed.

type KeyUpEvent

type KeyUpEvent struct{ KeyboardEvent }

The KeyUpEvent is fired when a key is released.

type KeyboardEvent

type KeyboardEvent struct {
	// Key represents the key value of the key represented by the event.
	Key string
	// Mod describes the modifier keys pressed during the event.
	Mod ModifierKeys
}

KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard.

type LineCap

type LineCap byte

LineCap represents the shape used to draw the end points of lines.

const (
	// CapButt squares off the ends of lines at the endpoints.
	CapButt LineCap = iota
	// CapRound rounds the ends of lines.
	CapRound
	// CapSquare squares off the ends of lines by adding a box with an equal
	// width and half the height of the line's thickness.
	CapSquare
)

type LineJoin

type LineJoin byte

LineJoin represents the shape used to join two line segments where they meet.

const (
	// JoinMiter joins connected segments by extending their outside edges to
	// connect at a single point, with the effect of filling an additional
	// lozenge-shaped area. This setting is affected by Context.SetMiterLimit.
	JoinMiter LineJoin = iota
	// JoinRound rounds off the corners of a shape by filling an additional
	// sector of disc centered at the common endpoint of connected segments.
	// The radius for these rounded corners is equal to the line width.
	JoinRound
	// JoinBevel fills an additional triangular area between the common
	// endpoint of connected segments, and the separate outside rectangular
	// corners of each segment.
	JoinBevel
)

type ModifierKeys added in v0.2.0

type ModifierKeys byte

ModifierKeys describes the modifier keys (Alt, Shift, Ctrl, Meta) pressed during an event.

func (ModifierKeys) AltKey added in v0.2.0

func (m ModifierKeys) AltKey() bool

AltKey returns true if the Alt (Option or ⌥ on OS X) key was active when the event was generated.

func (ModifierKeys) CtrlKey added in v0.2.0

func (m ModifierKeys) CtrlKey() bool

CtrlKey returns true if the Ctrl key was active when the event was generated.

func (ModifierKeys) MetaKey added in v0.2.0

func (m ModifierKeys) MetaKey() bool

MetaKey returns true if the Meta key (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key (⊞)) was active when the event was generated.

func (ModifierKeys) ShiftKey added in v0.2.0

func (m ModifierKeys) ShiftKey() bool

ShiftKey returns true if the Shift key was active when the event was generated.

type MouseButtons

type MouseButtons int

MouseButtons is a number representing one or more buttons. For more than one button pressed simultaneously, the values are combined (e.g., 3 is ButtonPrimary + ButtonSecondary).

const (
	// ButtonPrimary is the primary button (usually the left button).
	ButtonPrimary MouseButtons = 1 << iota
	// ButtonSecondary is the secondary button (usually the right button).
	ButtonSecondary
	// ButtonAuxiliary is the auxiliary button (usually the mouse wheel button
	// or middle button)
	ButtonAuxiliary
	// Button4th is the 4th button (typically the "Browser Back" button).
	Button4th
	// Button5th is the 5th button (typically the "Browser Forward" button).
	Button5th
	// ButtonNone stands for no button or un-initialized.
	ButtonNone MouseButtons = 0
)

type MouseDownEvent

type MouseDownEvent struct{ MouseEvent }

The MouseDownEvent is fired when a pointing device button is pressed.

Note: This differs from the ClickEvent in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the canvas. MouseDownEvent is fired the moment the button is initially pressed.

type MouseEvent

type MouseEvent struct {
	// Buttons encodes the buttons being depressed (if any) when the mouse
	// event was fired.
	Buttons MouseButtons
	// The X coordinate of the mouse pointer.
	X int
	// The Y coordinate of the mouse pointer.
	Y int
	// Mod describes the modifier keys pressed during the event.
	Mod ModifierKeys
}

MouseEvent represents events that occur due to the user interacting with a pointing device (such as a mouse).

type MouseMoveEvent

type MouseMoveEvent struct{ MouseEvent }

The MouseMoveEvent is fired when a pointing device (usually a mouse) is moved.

type MouseUpEvent

type MouseUpEvent struct{ MouseEvent }

The MouseUpEvent is fired when a button on a pointing device (such as a mouse or trackpad) is released. It is the counterpoint to the MouseDownEvent.

type Options added in v0.4.0

type Options struct {
	// Title sets the title of the browser tab/window.
	Title string
	// Width sets the width of the canvas.
	// If Width is not set (i.e. 0) a default value of 300 will be used.
	Width int
	// Height sets the height of the canvas.
	// If Height is not set (i.e. 0) a default value of 150 will be used.
	Height int
	// PageBackground configures the background color
	// of the served HTML page.
	// If PageBackground is not set (i.e. nil) a default value of
	// color.White will be used.
	PageBackground color.Color
	// EnabledEvents enables transmission of the given event types
	// from the client to the server.
	// It is sufficient to list the zero values of the events here.
	// CloseEvent is always implicitly enabled,
	// it doesn't have to be part of this slice.
	EnabledEvents []Event
	// MouseCursorHidden hides the mouse cursor on the canvas.
	MouseCursorHidden bool
	// ContextMenuDisabled disables the context menu on the canvas.
	ContextMenuDisabled bool
	// ScaleToPageWidth scales the canvas to the full horizontal extent
	// of the page in the browser window.
	// This scaling does not change the width within the coordinate system
	// as set by Width.
	ScaleToPageWidth bool
	// ScaleToPageHeight scales the canvas to the full vertical extent
	// of the page in the browser window.
	// This scaling does not change the height within the coordinate system
	// as set by Height.
	ScaleToPageHeight bool
	// ReconnectInterval configures the client to reconnect after
	// the given duration if the WebSocket connection was lost.
	// The client tries to reconnect repeatedly until it is successful.
	// If ReconnectInterval is not set (i.e. 0) the canvas will not try
	// to reconnect if the connection was lost.
	ReconnectInterval time.Duration
}

Options configure various aspects of the canvas. The zero value of this struct is useful out of the box, but most users probably want to set at least Width and Height.

type Pattern

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

Pattern represents a pattern, based on an image, created by the Context.CreatePattern method. It can be used with the Context.SetFillStylePattern and Context.SetStrokeStylePattern methods.

The pattern should be released with the Release method when it is no longer needed.

func (*Pattern) Release

func (p *Pattern) Release()

Release releases the pattern on the client side.

type PatternRepetition

type PatternRepetition byte

PatternRepetition indicates how to repeat a pattern's image.

const (
	// PatternRepeat repeats the image in both directions.
	PatternRepeat PatternRepetition = iota
	// PatternRepeatX repeats the image only horizontally.
	PatternRepeatX
	// PatternRepeatY repeats the image only vertically.
	PatternRepeatY
	// PatternNoRepeat repeats the image in neither direction.
	PatternNoRepeat
)

type TextAlign

type TextAlign byte

TextAlign represents the text alignment used when drawing text.

const (
	// AlignStart means the text is aligned at the normal start of the line
	// (left-aligned for left-to-right locales, right-aligned for right-to-left
	// locales).
	AlignStart TextAlign = iota
	// AlignEnd means the text is aligned at the normal end of the line
	// (right-aligned for left-to-right locales, left-aligned for right-to-left
	// locales).
	AlignEnd
	// AlignLeft means the text is left-aligned.
	AlignLeft
	// AlignRight means the text is right-aligned.
	AlignRight
	// AlignCenter means the text is centered.
	AlignCenter
)

type TextBaseline

type TextBaseline byte

TextBaseline represents the text baseline used when drawing text.

const (
	// BaselineAlphabetic means the text baseline is the normal alphabetic
	// baseline.
	BaselineAlphabetic TextBaseline = iota
	// BaselineIdeographic means the text baseline is the ideographic baseline;
	// this is the bottom of the body of the characters, if the main body of
	// characters protrudes beneath the alphabetic baseline.
	// (Used by Chinese, Japanese, and Korean scripts.)
	BaselineIdeographic
	// BaselineTop means the text baseline is the top of the em square.
	BaselineTop
	// BaselineBottom means the text baseline is the bottom of the bounding
	// box. This differs from the ideographic baseline in that the ideographic
	// baseline doesn't consider descenders.
	BaselineBottom
	// BaselineHanging means the text baseline is the hanging baseline.
	// (Used by Tibetan and other Indic scripts.)
	BaselineHanging
	// BaselineMiddle means the text baseline is the middle of the em square.
	BaselineMiddle
)

type Touch

type Touch struct {
	// Identifier is a unique identifier for this Touch object. A given touch
	// point (say, by a finger) will have the same identifier for the duration
	// of its movement around the surface. This lets you ensure that you're
	// tracking the same touch all the time.
	Identifier uint32
	// The X coordinate of the touch point.
	X int
	// The Y coordinate of the touch point.
	Y int
}

Touch represents a single contact point on a touch-sensitive device. The contact point is commonly a finger or stylus and the device may be a touchscreen or trackpad.

type TouchCancelEvent

type TouchCancelEvent struct{ TouchEvent }

The TouchCancelEvent is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).

type TouchEndEvent

type TouchEndEvent struct{ TouchEvent }

The TouchEndEvent is fired when one or more touch points are removed from the touch surface.

type TouchEvent

type TouchEvent struct {
	// Touches is a TouchList of all the Touch objects representing all current
	// points of contact with the surface, regardless of target or changed
	// status.
	Touches TouchList
	// ChangedTouches is a TouchList of all the Touch objects representing
	// individual points of contact whose states changed between the previous
	// touch event and this one.
	ChangedTouches TouchList
	// TargetTouches is a TouchList of all the Touch objects that are both
	// currently in contact with the touch surface and were also started on the
	// same element that is the target of the event.
	TargetTouches TouchList
	// Mod describes the modifier keys pressed during the event.
	Mod ModifierKeys
}

The TouchEvent is fired when the state of contacts with a touch-sensitive surface changes. This surface can be a touch screen or trackpad, for example. The event can describe one or more points of contact with the screen and includes support for detecting movement, addition and removal of contact points, and so forth.

Touches are represented by the Touch object; each touch is described by a position, size and shape, amount of pressure, and target element. Lists of touches are represented by TouchList objects.

type TouchList

type TouchList []Touch

TouchList represents a list of contact points on a touch surface. For example, if the user has three fingers on the touch surface (such as a screen or trackpad), the corresponding TouchList object would have one Touch object for each finger, for a total of three entries.

type TouchMoveEvent

type TouchMoveEvent struct{ TouchEvent }

The TouchMoveEvent is fired when one or more touch points are moved along the touch surface.

type TouchStartEvent

type TouchStartEvent struct{ TouchEvent }

The TouchStartEvent is fired when one or more touch points are placed on the touch surface.

type WheelEvent

type WheelEvent struct {
	MouseEvent
	// DeltaX represents the horizontal scroll amount.
	DeltaX float64
	// DeltaY represents the vertical scroll amount.
	DeltaY float64
	// DeltaZ represents the scroll amount for the z-axis.
	DeltaZ float64
	// DeltaMode represents the unit of the delta values' scroll amount.
	DeltaMode DeltaMode
}

The WheelEvent is fired due to the user moving a mouse wheel or similar input device.

Directories

Path Synopsis
example
breakout
Breakout is a classic arcade game where the player controls a paddle at the bottom of the screen to bounce a ball and break through a wall of bricks at the top of the screen.
Breakout is a classic arcade game where the player controls a paddle at the bottom of the screen to bounce a ball and break through a wall of bricks at the top of the screen.
clock
Clock draws an animated clock, showing the current time.
Clock draws an animated clock, showing the current time.
cloth
Cloth is an interactive physics simulation of a cloth that can be torn by clicking and dragging the mouse.
Cloth is an interactive physics simulation of a cloth that can be torn by clicking and dragging the mouse.
hilbert
Hilbert draws a graphic pattern consisting of multiple superimposed Hilbert curves using the recursive algorithm described in the book "Algorithms and Data Structures" by N. Wirth.
Hilbert draws a graphic pattern consisting of multiple superimposed Hilbert curves using the recursive algorithm described in the book "Algorithms and Data Structures" by N. Wirth.
image
Image demonstrates how to draw image data on the canvas.
Image demonstrates how to draw image data on the canvas.
particles
Particles is a non-interactive canvas demo showing colorful animated particles.
Particles is a non-interactive canvas demo showing colorful animated particles.
retro-synthwave
Retro-synthwave is an animated demo by Victor Ribeiro.
Retro-synthwave is an animated demo by Victor Ribeiro.
trail
Trail is an interactive animation of rotating particles that follow the mouse or touch pointer.
Trail is an interactive animation of rotating particles that follow the mouse or touch pointer.

Jump to

Keyboard shortcuts

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