# old version Canvas Migration Guide

Mini Program. old version canvas interface Is no longer maintained, this guide will guide you on how to migrate to the new version Canvas 2D interface

# Characteristic difference

old version canvas interface Canvas 2D interface
Same layer rendering Not support Support
API support Partially supported Support all Web standard
draw Asynchronous rendering Synchronous rendering
performance low high

# Migration steps

# Step 1: Modify WXML

<canvas canvas-id="myCanvas" />
<!-- Amended to read -->
<canvas id="myCanvas" type="2d" />

old version canvas Interface Usage canvas-id Attribute unique identifier canvasnew edition Canvas 2D Can be used directly id Logo.

Also need to give canvas Add to type="2d" Property is identified as a new version Canvas 2D Interface.

# Step 2: Modify Get CanvasContext

const context = wx.createCanvasContext('myCanvas')
//
// Amended to read
//
wx.createSelectorQuery()
    .select('#myCanvas') // in WXML Filled in. id
    .node(({ node: canvas }) => {
        const context = canvas.getContext('2d')
    })
    .exec()

old version canvas Interface Usage wx.createCanvasContext synchronizationObtain CanvasContext

new edition Canvas 2D The interface needs to be passed first SelectorQuery asynchronousObtain Canvas object, and then through Canvas.getContext Get the rendering context RenderingContext

# Step 3: Canvas Size Initialization

// old version canvas Cannot modify width and height
wx.createSelectorQuery()
    .select('#myCanvas') // in WXML Filled in. id
    .fields({ node: true, size: true })
    .exec((res) => {
        // Canvas object
        const canvas = res[0].node
        // Canvas The actual drawing width and height of the canvas
        const renderWidth = res[0].width
        const renderHeight = res[0].height
        // Canvas Draw context
        const ctx = canvas.getContext('2d')

        // Initializes the canvas size 
        const DPR  = wx.getWindowInfo ().pixelRatio 
        canvas.width = renderWidth * DPR 
        canvas.height = renderHeight * DPR 
        ctx.scale(DPR,  DPR )
    })

old version canvas The canvas size of the interface is determined by the actual render width and cannot be modified by the developer.

new edition Canvas 2D Interface allows developers to freely modify the logical size of the canvas. The default width and height is 300*150。

On different devices, there are physical pixels and logical pixels are not equal, so generally we need to use the wx.getWindowInfo Gets the pixel ratio of the device, multiplied by the canvas The actual size.

# Step 4: Modify the drawing method

// Several draw calls
context.fillRect(0, 0, 50, 50)
context.fillRect(20, 20, 50, 50)

context.draw(false, () => {
    // This is done.
    console.log('draw done')
})

//
// Amended to read
//

// Empty the canvas before painting
context.clearRect(0, 0, canvas.width, canvas.height)
// Several draw calls
context.fillRect(0, 0, 50, 50)
context.fillRect(20, 20, 50, 50)

// This is done.
console.log('draw done')

old version canvas Interface drawing requires a call CanvasContext.draw Will be drawn, and the drawing process isasynchronousYou need to wait for the draw completion callback before you can proceed to the next step.

new edition Canvas 2D Interface is no longer required to call the draw Function, all drawing methods willsynchronizationOnto the canvas.

It is important to note that CanvasContext.draw The first argument to the function controls whether the previous draw is preserved before drawing (the default is False, that is, not retained), if set to False, then after migrating to the new interface, you need to pass the clearRect Clear the canvas.

# Step 5: Modify the picture to draw

context.drawImage(
    'https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_wx_logo.png',
    0,
    0,
    150,
    100,
)
//
// Amended to read
//
const image = canvas.createImage()
image.onload = () => {
    context.drawImage(
        image,
        0,
        0,
        150,
        100,
    )
}
image.src = 'https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_wx_logo.png'

old version canvas interface CanvasContext.drawImage Direct input image url Draw.

new edition Canvas 2D The interface needs to be passed first Canvas.createImage Create a picture object,onload The picture is loaded after the callback is triggered, and then the picture object is passed in context.drawImage Draw.

# Remaining interface adjustments

# wx.canvasToTempFilePath

wx.canvasToTempFilePath({
    canvasId:  'myCanvas',
    success(res) {
        //
    }
})
//
// Amended to read
//
wx.canvasToTempFilePath({
    canvas: canvas,
    success(res) {
        //
    }
})

old version canvas Interface incoming canvas-id

new edition Canvas 2D Interface needs to be passed directly into the Canvas Example

# wx.canvasPutImageData

wx.canvasPutImageData({
    canvasId:  'myCanvas',
    x: 0,
    y: 0,
    width: 1,
    height: 1,
    data: data,
    success (res) {
        // after put image Data
    }
})
//
// Amended to read
//
const context = canvas.getContext('2d')
context.putImageData(data, 0, 0, 0, 0, 1, 1)
// after put image Data

new edition canvas Not support wx.canvasPutImageData, should be used context.putImageData Instead.

# wx.canvasGetImageData

wx.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
    }
})
//
// Amended to read
//
const context = canvas.getContext('2d')
const imageData = context.getImageData(0, 0, 100, 100)
console.log(imageData.width) // 100
console.log(imageData.height) // 100
console.log(imageData.data instanceof Uint8ClampedArray ) // true
console.log(imageData.data.length) // 100 * 100 * 4

new edition canvas Not support wx.canvasGetImageData, should be used context.getImageData Instead.

# wx.loadFontFace

wx.loadFontFace({
  family: 'Bitstream Vera Serif Bold',
  source: 'url("https://sungd.github.io/Pacifico.ttf )',
  success: console.log
})
//
// Amended to read
//
wx.loadFontFace({
  family: 'Bitstream Vera Serif Bold',
  source: 'url("https://sungd.github.io/Pacifico.ttf )',
  scopes: ['webview', 'native'],
  success: console.log
})

new edition Canvas 2D The interface needs to be scopes Set up native