Canvas
Canvas Canvas Provides a drawing interface on which you can draw anything.
1. Basic usage
Step 1: Add canvas component in WXML
<!-- 2d type canvas -->
<canvas id="myCanvas" type="2d" style="border: 1px solid; width: 300px; height: 150px;" />First, you need to add it in WXML Canvas Canvas
Specify id='myCanvas' to uniquely identify a canvas, which is used to obtain the Canvas object later.
Specify type to define the canvas type. This example uses type='2d'.
Step 2: Get the Canvas object and rendering context
wx.createSelectorQuery()
.select('#myCanvas') // id in WXML
.fields({ node: true, size: true })
.exec((res) => {
// Canvas Object
const canvas = res[0].node
// rendering context
const ctx = canvas.getContext('2d')
})by SelectorQuerySelect the canvas from the previous step to get Canvas
Then through Canvas.getContext, we can get the rendering context RenderingContext
Subsequent canvas operations and rendering operations need to be implemented through these two objects.
Step 3: Initialize Canvas
wx.createSelectorQuery()
.select('#myCanvas') // id in WXML
.fields({ node: true, size: true })
.exec((res) => {
// Canvas Object
const canvas = res[0].node
// rendering context
const ctx = canvas.getContext('2d')
// The actual drawing width and height of the Canvas.
const width = res[0].width
const height = res[0].height
// Initialise canvas size
const dpr = wx.getWindowInfo().pixelRatio
canvas.width = width * dpr
canvas.height = height * dpr
ctx.scale(dpr, dpr)
})The width and height of the canvas are divided into rendering width and height and logical width and height:
- The rendering width and height is the actual width and height of the canvas on the page, that is, by boundingClientRectThe size requested.
- The logical width and height are the logical width and height of the canvas during the rendering process. If you draw a rectangle with the same logical width and height, the rectangle will eventually occupy the entire canvas. The default logical width and height is 300 * 150.
- On different devices, there are cases where physical pixels and logical pixels are not equal, so we generally need to use wx.getWindowInfoto obtain the pixel ratio of the device, multiply it by the rendering size of the canvas, as the logical size of the canvas.
Step 4: Draw
// Omit the initialisation steps above, the canvas object and ctx rendering context have already been obtained
// Empty the canvas
ctx.clearRect(0, 0, width, height)
// Drawing a red square
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);
// Drawing Blue Translucent Squares
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
ctx.fillRect(30, 30, 50, 50);by Rendering context, we can draw anything on the canvas
2. Advanced use
2.1 Draw pictures
// Omit the initialisation steps above, the canvas object and ctx rendering context are already obtained
// The image object
const image = canvas.createImage()
// Image load completion callback
image.onload = () => {
// Draw the image to the canvas
ctx.drawImage(image, 0, 0)
}
// Set the image src
image.src = 'https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_wx_logo.png'Through the drawing api on Canvas.createImageWe can create picture objects and load pictures. When the picture loading is completed and the onload callback is triggered, use ctx.drawImage to draw the picture on the canvas.
2.2 Generate pictures
// Omitting the initialisation steps above, the canvas object and the ctx rendering context are already acquired
// Drawing a red square
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);
// Drawing Blue Translucent Squares
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
ctx.fillRect(30, 30, 50, 50);
// Generate Image
wx.canvasToTempFilePath({
canvas,
success: res => {
// Path to the generated image temporary file
const tempFilePath = res.tempFilePath
},
})Through the drawing api on wx.canvasToTempFilePathInterface, which can generate temporary image files from the content on canvas.
2.3 Frame Animation
// Omit the initialisation steps above, the canvas object and the ctx rendering context have already been fetched.
const startTime = Date.now()
// Frame rendering callbacks
const draw = () => {
const time = Date.now()
// Calculate the elapsed time
const elapsed = time - startTime
// Calculate the animation position
const n = Math.floor(elapsed / 3000)
const m = elapsed % 3000
const dx = (n % 2 ? 0 : 1) + (n % 2 ? 1 : -1) * (m < 2500 ? easeOutBounce(m / 2500) : 1)
const x = (width - 50) * dx
// Rendering
ctx.clearRect(0, 0, width, height)
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(x, height / 2 - 25, 50, 50);
// Register for next frame rendering
canvas.requestAnimationFrame(draw)
}
draw()Through the drawing api on Canvas.requestAnimationFrameYou can register the animation frame callback and draw the animation frame by frame in the callback.
2.4 Custom font
Through the drawing api on wx.loadFontFaceYou can load custom fonts for Canvas