0

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

4

1 回答 1

1

华为快应用中心ctx每次调用该getContext方法时都会创建一个对象,因此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");

  }

}

 
于 2021-02-23T06:14:41.647 回答