Images Drawn by the canvas Component Cannot Be Displayed in the Album

Symptom

After an image drawn by the canvas component is saved to the album, the image cannot be displayed in the album. Only a black background image is displayed.

The image with green background in the following figure is drawn by the canvas component.

After the image is saved to the album, the display result is as shown in the following figure.

Cause Analysis

Huawei Quick App Center creates a ctx object each time when it calls the getContext method, and therefore different ctx objects will be returned. Some of these ctx objects are empty. An empty ctx object may be obtained in a random selection. As a result, the image saved may have no content. The code is as follows:

Code for using canvas to draw an image:

Code for saving the image:

Solution

Define ctx as a global variable and check whether it is empty. Assign an initial value to an empty ctx.

Optimized code: