Skip to content

Canvas

createCanvasContext

CanvasContext ft.createCanvasContext(string canvasId, Object this)

create canvas Drawing context CanvasContext object

parameter

string canvasId

To get the context canvas assembly canvas-id attribute

Object this

Under a custom component, this for the current component instance, indicates that under this custom component the lookup for the canvas-id of canvas If omitted, does not look inside any custom components

Return value

CanvasContext

canvasToTempFilePath

CanvasContext ft.canvasToTempFilePath(Object object, Object this) Generates a specified size picture by exporting the contents of the specified area of the current canvas. in draw() Callback call this method to ensure that the picture export success

parameter

Object object

attributetypeDefault valuesRequiredIntroductionsMinimum version
xnumber0noThe upper-left abscissa of the specified canvas area
ynumber0noThe upper-left ordinate of the specified canvas area
widthnumbercanvas-width-xnoWidth of the specified canvas area
heightnumbercanvas-height-ynoHeight of the specified canvas area
destWidthnumberwidth*Screen pixel densitynoWidth of output picture
destHeightnumberheight*Screen pixel densitynoHeight of output picture
canvasIdstringnoCanvas identity, passed in canvas Component canvas-id
canvasObjectnoCanvas identity, passed in canvas Component instance (canvas type="2d" This property is used when the.
fileTypestringpngnoType of destination filepng or jpg
qualitynumbernoThe quality of the picture is currently only jpg Effective. The range is (0, 1]When not within the scope of 1.0 Deal with.unsupported
successfunctionnoInterface calls the successful callback function
failfunctionnoInterface calls failed callback functions
completefunctionnoInterface calls the end of the callback function (call success or failure will be executed)

object.fileType Legal value

valueIntroductionsMinimum version
jpgjpg picture
pngpng picture

object.success callback

parameter

Object res

attributetypeIntroductions
tempFilePathstringTemporary path to build file (Local path)

Object this

Under a custom component, the this of the current component instance to manipulate within the component canvas assembly

sample code

javascript
ft.canvasToTempFilePath({
  x: 100,
  y: 200,
  width: 50,
  height: 50,
  destWidth: 100,
  destHeight: 100,
  canvasId: 'myCanvas',
  success(res) {
    console.log(res.tempFilePath)
  }
})

canvasPutImageData

CanvasContext ft.canvasPutImageData(Object object, Object this) Draws pixel data to the canvas. Under custom components, the second parameter passes in the custom component instance This to operate within the component &ltcanvas&gt assembly

parameter

Object object

attributetypeDefault valuesRequiredIntroductions
canvasIdstringyesCanvas identity, passed in canvas Component canvas-id Property.
dataUint8ClampedArrayyesImage pixel data, one-dimensional array, every four items representing a pixel rgba
xnumberyesPosition offset of source image data in the target canvas x Offset in the axial direction)
ynumberyesPosition offset of source image data in the target canvas y Offset in the axial direction)
widthnumberyesWidth of the rectangular region of source image data
heightnumberyesHeight of rectangular region of source image data
successfunctionnoInterface calls the successful callback function
failfunctionnoInterface calls failed callback functions
completefunctionnoInterface calls the end of the callback function (call success or failure will be executed)

Object this

Under a custom component, the this of the current component instance to manipulate within the component canvas assembly

sample code

javascript
const data = new Uint8ClampedArray([255, 0, 0, 1])
ft.canvasPutImageData({
  canvasId: 'myCanvas',
  x: 0,
  y: 0,
  width: 1,
  height: 1,
  data: data,
  success (res) {}
})

canvasGetImageData

CanvasContext ft.canvasGetImageData(Object object, Object this) Obtain canvas The pixel data implied by the region.

parameter

Object object

attributetypeDefault valuesRequiredIntroductions
canvasIdstringyesCanvas identity, passed in canvas Component canvas-id Property.
xnumberyesThe upper-left abscissa of the rectangular region of the image data to be extracted
ynumberyesThe upper-left ordinate of the rectangular region of image data to be extracted
widthnumberyesWidth of rectangular region of image data to be extracted
heightnumberyesThe height of the rectangular area of image data to be extracted
successfunctionnoInterface calls the successful callback function
failfunctionnoInterface calls failed callback functions
completefunctionnoInterface calls the end of the callback function (call success or failure will be executed)

object.success callback

parameter

Object res

attributetypeIntroductions
widthnumberWidth of image data rectangle
heightnumberHeight of image data rectangle
dataUint8ClampedArrayImage pixel data, one-dimensional array, every four items representing a pixel rgba

Object this

Under a custom component, the this of the current component instance to manipulate within the component canvas assembly

sample code

javascript
ft.canvasGetImageData({
  canvasId: 'myCanvas',
  x: 0,
  y: 0,
  width: 100,
  height: 100,
  success(res) {
    console.log(res.width) // 100
    console.log(res.height) // 100
    console.log(res.data instanceof Uint8ClampedArray) // true
    console.log(res.data.length) // 100 * 100 * 4
  }
})

CanvasContext

canvas Component's drawing context. CanvasContext Is the old interface, new edition Canvas 2D Interface and Web Consistent

attribute

  • string|CanvasGradient fillStyle
    Fill the color. Use the same CanvasContext.setFillStyle()。

  • string|CanvasGradient strokeStyle
    Border color. Use the same CanvasContext.setStrokeStyle()。

  • number shadowOffsetX
    Horizontal offset of shadow relative to shape

  • number shadowOffsetY
    The vertical deviation of the shadow from the shape

  • number shadowColor
    Color of Shadows

  • number shadowBlur
    Blur level of shadow

  • number lineWidth
    The width of the line. Use the same CanvasContext.setLineWidth()。

  • string lineCap
    The endpoint style of the line. Use the same CanvasContext.setLineCap()。

  • string lineJoin
    Intersection style of lines. Use the same CanvasContext.setLineJoin()。

lineJoin Legal value

valueIntroductionsMinimum version
orderbevel
roundFillet
miterCusp
  • number miterLimit
    Max miter length. Use the same CanvasContext.setMiterLimit()。

  • number lineDashOffset
    Dashed offset, initial value 0

  • string font
    Properties of the current font style. accord with CSS font grammar of DOMString A string that requires, at a minimum, the font size and font family name. Default value is 10px sans-serif

  • number globalAlpha
    Global brush transparency. range 0-1,0 For complete transparency, 1 Indicates complete opacity

  • string globalCompositeOperation
    The type of composition operation applied when drawing a new shape. The current Android version is only available fill Fill block synthesis for stroke The synthetic effect of the segments is source-over。

The following operations are currently supported

method

  • CanvasContext.draw(boolean reserve, function callback)
    Draws a description (path, deformation, style) previously in the drawing context to canvas In

  • CanvasGradient CanvasContext.createLinearGradient(number x0, number y0, number x1, number y1)
    Creates a linear gradient color. ReturnedCanvasGradientThe object needs to use the CanvasGradient.addColorStop() To specify gradient points, you need at least two.

  • CanvasGradient CanvasContext.createCircularGradient(number x, number y, number r)
    Create a circular gradient color. The starting point is in the center of the circle and the ending point is the circle. ReturnedCanvasGradientThe object needs to use the CanvasGradient.addColorStop() To specify gradient points, you need at least two

  • CanvasContext.createPattern(string image, string repetition)
    A method that creates a pattern for a specified image, repeating a meta image in a specified direction

  • Object CanvasContext.measureText(string text)
    Measure text size information. Currently only the text width is returned. Synchronization interface

  • CanvasContext.save()
    Save the drawing context

  • CanvasContext.restore()
    Restores a previously saved drawing context

  • CanvasContext.beginPath()
    Start creating a path. Need to call fill or stroke Will use the path to fill or stroke

  • CanvasContext.moveTo(number x, number y)
    Moves the path to the specified point on the canvas without creating a line. use stroke Method to draw lines

  • CanvasContext.lineTo(number x, number y)
    Adds a new point, and then creates a line from the last specified point to the target point. use stroke Method to draw lines

  • CanvasContext.quadraticCurveTo(number cpx, number cpy, number x, number y)
    Creates a quadratic Bezier curve path. The starting point of a curve is the previous point in the path

  • CanvasContext.bezierCurveTo(number cp1x, number cp1y, number cp2x, number cp2y, number x, number y)
    Create a cubic bezier curve path. The starting point of a curve is the previous point in the path

  • CanvasContext.arc(number x, number y, number r, number sAngle, number eAngle, boolean counterclockwise)
    Create an arc Create a circle that specifies the starting radian as 0, terminating radians 2 * Math.PI。 use stroke or fill Method to come in canvas Draw an arc in

  • CanvasContext.rect(number x, number y, number width, number height)
    Creates a rectangular path. Need fill or stroke Method draws the rectangle to the canvas in

  • CanvasContext.arcTo(number x1, number y1, number x2, number y2, number radius)
    Draws arc paths based on control points and radius

  • CanvasContext.clip()
    Cut arbitrary shapes and sizes from the original canvas. Once a region is clipped, all subsequent drawings are restricted to the region being clipped (no access to other regions of the canvas). Can be used clip Method by using save Method to save the current canvas area and at any later time pass therestoreMethod to restore it

  • CanvasContext.fillRect(number x, number y, number width, number height)
    Fills a rectangle. use setFillStyle Set the fill color for the rectangle. If not set, the default is black

  • CanvasContext.strokeRect(number x, number y, number width, number height)
    Draw a rectangle(Unfilled)。 use setStrokeStyle Sets the color of the rectangular line. If not set, the default is black

  • CanvasContext.clearRect(number x, number y, number width, number height)
    Clears the contents of the canvas inside the rectangular area

  • CanvasContext.fill()
    Populates the contents of the current path. The default fill color is black

  • CanvasContext.stroke()
    Draws a border for the current path. The default color is black

  • CanvasContext.closePath()
    Close a path. Will connect the beginning and the end. If the path is closed and not called fill or stroke And opens a new path where the previous path will not be rendered

  • CanvasContext.scale(number scaleWidth, number scaleHeight)
    After the call, the following paths are created with their ordinate and abscissa scaling. Multiple calls multiply.

  • CanvasContext.rotate(number rotate)
    Rotate the current axis clockwise from the origin. The rotation angles of multiple invocations stack up. The origin can be used translate Method modification

  • CanvasContext.translate(number x, number y)
    For the origin of the current coordinate system (0, 0) Transform. The default coordinate origin is the upper-left corner of the page

  • CanvasContext.drawImage(string imageResource, number sx, number sy, number sWidth, number sHeight, number dx, number dy, number dWidth, number dHeight)
    Draw Image to Canvas

  • CanvasContext.strokeText(string text, number x, number y, number maxWidth)
    Given (x, and) A Method of Text Stroke for Position Drawing

  • CanvasContext.transform(number scaleX, number skewX, number skewY, number scaleY, number translateX, number translateY)
    Method for Overlaying the Current Transformation Multiple Times Using Matrices

  • CanvasContext.setTransform(number scaleX, number skewX, number skewY, number scaleY, number translateX, number translateY)
    Method for resetting (overwriting) the current transformation using a matrix

  • CanvasContext.setFillStyle(string|CanvasGradient color)
    Set the fill color

  • CanvasContext.setStrokeStyle(string|CanvasGradient color)
    Set stroke color

  • CanvasContext.setShadow(number offsetX, number offsetY, number blur, string color)
    Set the shadow style

  • CanvasContext.setGlobalAlpha(number alpha)
    Sets global brush transparency

  • CanvasContext.setLineWidth(number lineWidth)
    Set the width of the line

  • CanvasContext.setLineJoin(string lineJoin)
    Set the intersection style of the line

  • CanvasContext.setLineCap(string lineCap)
    Set the endpoint style of a line

  • CanvasContext.setLineDash(Array.<number> pattern, number offset)
    Sets the dashed line style

  • CanvasContext.setMiterLimit(number miterLimit)
    Sets the maximum miter length. Miter length refers to the distance between the inner and outer corners where two lines meet. when CanvasContext.setLineJoin() for miter Only when it's effective. If the maximum inclined length is exceeded, the connection will be lineJoin for order To display

  • CanvasContext.fillText(string text, number x, number y, number maxWidth)
    Draws filled text on canvas

  • CanvasContext.setFontSize(number fontSize)
    Set font size

  • CanvasContext.setTextAlign(string align)
    Set text alignment

  • CanvasContext.setTextBaseline(string textBaseline)
    Set the vertical alignment of text

Canvas

Canvas instances, available via SelectorQuery.

If the canvas is configured with native prop attribute, it will be handled with native rendering, supported from base library 2.12.1, iOS/Android 2.35.1.

html
<!-- canvas.fxml -->
<canvas type="2d" id="canvas"></canvas>
js
// canvas.js
Page({
  onReady() {
    const query = ft.createSelectorQuery().select('#canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        const dpr = 2
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.fillRect(0, 0, 100, 100)
      })
  }
})

Canvas.getContext()

This method returns Canvas Drawing context

The canvas obtained by the selector query has the same context api as the web canvas

Canvas.createImage()

Create a picture object. Support in 2D Canvas and WebGL Canvas Under use, But does not support mixing 2D and WebGL The method

js
const img = canvas.createImage()
img.onload = () => {
  const pat = context.createPattern(img, "repeat")
  context.fillStyle = pat
  context.rect(0, 0, 150, 100)
  context.fill()
}
// Image path
img.src = '../../../image/icon_cloud_HL.png'

CanvasGradient.addColorStop

CanvasGradient.addColorStop(number stop, string color)

Adds a gradient point for the color. Less than minimum stop The part of the stop of color To render, greater than the maximum stop The part of the stop of color To render

parameter

attributetypeIntroductions
stopnumberRepresents the position between the start and end of a gradient, the range 0-1。
colorstringThe color of the gradient point.

sample code

javascript
const ctx = ft.createCanvasContext('myCanvas')

// Create circular gradient
const grd = ctx.createLinearGradient(30, 10, 120, 10)
grd.addColorStop(0, 'red')
grd.addColorStop(0.16, 'orange')
grd.addColorStop(0.33, 'yellow')
grd.addColorStop(0.5, 'green')
grd.addColorStop(0.66, 'cyan')
grd.addColorStop(0.83, 'blue')
grd.addColorStop(1, 'purple')

// Fill with gradient
ctx.setFillStyle(grd)
ctx.fillRect(10, 10, 150, 80)
ctx.draw()
})

Color

Color. Can be expressed in the following ways canvas Colors used in::

RGB Colour: Such as 'rgb(255, 0, 0)'

RGBA Colour: such as 'rgba(255, 0, 0, 0.3)'

16 Base color: Such as '#FF0000'

Predefined colors: Such as 'red'

Image

Picture object

attribute

string src

Pictorial URL

number width

True width of picture

number height

True height of picture

string referrerPolicy

origin: Send the full referrer no-referrer: Do not send. Format fixed to https://servicewechat.com/{appid}/{version}/page-frame.htmlWhere {appid} For Mini Program appid,{version} Is the version number of the Mini Program, which is 0 Represents a development version, a trial version, and a review version with a version number of devtools Represented as developer tools and the rest as official versions

function onload

A callback function that triggers when the picture is loaded

function onerror

A callback function triggered after an error in picture loading

ImageData

ImageData object

attribute

number width

Use Pixel Description ImageData The actual width of

number height

Use Pixel Description ImageData Actual height

Uint8ClampedArray data

One-dimensional array containing the RGBA Sequential data, data usage 0 to Integer representation of 255 inclusive

OffscreenCanvas

Off-screen canvas Example, you can use the wx.createOffscreenCanvas Create

attribute

number width

Canvas width

number height

Canvas height

OffscreenCanvas.createImage()

Create a picture object.

Return value

Image

Be careful not to mix webgl and 2d Canvas to create a picture object, please note that when using the canvas Self createImage Create a picture object.

OffscreenCanvas.getContext()

This method returns OffscreenCanvas Drawing context

parameter

string contextType

Drawing context type, which requires the createOffscreenCanvas Passed in when type Agreement

contextType Legal value

valueIntroductionsMinimum version
webglWebgl type context
2d2d type context

Return value

RenderingContext

Be careful not to mix webgl and 2d Drawing context, incoming contextType You have to work with wx.createOffscreenCanvas Incoming type Same type.