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

问题描述

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

enter image description here

解决方法

华为快应用中心每次调用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,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,);

  }

  img.onerror = function () {

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

  }

}

 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...