canvas组件绘制的图片在相册中无法显示

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

canvas组件绘制的图片保存到相册后,无法在相册中显示。仅显示黑色背景图像。如何保证图片存入相册后正常?

华为快应用中心每次调用getContext方法时都会创建一个ctx对象,因此会返回不同的ctx对象。其中一些 ctx 对象是空的。随机选择可能会得到一个空的ctx对象。因此,保存的图像可能没有内容。代码如下:

使用canvas绘制图像的代码:

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 loaded successfully");

    ctx.drawImage(img, 10, 10, 300, 300, );

  }

  img.onerror = function () {

console.log("Failed to load the image");

  }

},

图片保存代码:

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.');

    }

  })

}

解决方案

定义ctx为全局变量,检查是否为空。为空 ctx.

分配初始值

优化代码:

var ctx; // Define a global variable.

pic() {

if (!ctx) {// Check whether a ctx object is empty. If it is empty, assign the 2d value 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 loaded successfully");

    ctx.drawImage(img, 10, 10, 300, 300, );

  }

  img.onerror = function () {

console.log("Failed to load the image");

  }

}