Problem phenomenon:

The content drawn by the Canvas component is exported and the generated picture is saved to the album. After entering the album, you can not see the drawn content but only a black background picture when opening the picture.

The green background in the figure below is what the Canvas component draws.

Saved to the album effect picture is as follows:

Problem analysis:

Huawei quick application engine will call the getContext method to create CTX each time, and will return different CTX objects. Some CTX objects will contain content, and some CTX objects will be empty. When obtaining CTX objects, it will obtain empty CTX objects randomly, resulting in no content in the saved image.

Canvas drawing code:

 pic() {
      var test = this.$element("canvas");
      var ctx = test.getContext("2d");
      var img = new Image();
      img.src = "http://www.huawei.com/Assets/CBG/img/logo.png";
      img.onload = function () {
        console.log("Image loading completed");
        ctx.drawImage(img, 10.10.300.300,); } img.onerror = function () { console.log("Image loading shibai"); }},Copy the code

Save the image code:

save() {
      var test = this.$element("canvas");
      test.toTempFilePath({
        fileType: "jpg",
        quality: 1.0,
        success: (data) => {
          console.log(`Canvas toTempFilePath success ${data.uri}`)
          console.log(`Canvas toTempFilePath success ${data.tempFilePath}`)
          media.saveToPhotosAlbum({
            uri: data.uri,
            success: function (ret) {
              console.log("save success: ");
            },
            fail: function (data, code) {
              console.log("handling fail, code=" + code);
            }
          })
        },
        fail: (data) => {
          console.log('Canvas toTempFilePath data =' + data);
        },
        complete: () => {
          console.log('Canvas toTempFilePath complete.'); }})}Copy the code

Solution: define CTX as a global variable, perform non-null judgment on CTX, if it is null, initialize and save.

The optimized code is as follows:

var ctx; // Define a global
    pic() {
      if(! ctx) {If CTX is empty, assign "2d" to it
        var test = this.$element("canvas");
        var tt = test.getContext("2d");
        ctx = tt;
      }
      var img = new Image();
      img.src = "http://www.huawei.com/Assets/CBG/img/logo.png";
      img.onload = function () {
        console.log("Image loading completed");
        ctx.drawImage(img, 10.10.300.300,); } img.onerror = function () { console.log("Image loading shibai"); }}Copy the code

For more details, see:

Faster application development guide: developer.huawei.com/consumer/cn…

Quick application Canvas component:

Developer.huawei.com/consumer/cn…

Canvas interface:

Developer.huawei.com/consumer/cn…


The original link: developer.huawei.com/consumer/cn… Author: AppGallery Connect