问题描述
canvas 组件绘制的图片保存到相册后,图片无法在相册中显示。仅显示黑色背景图像。图片保存到相册后如何保证图片正常?
解决方法
华为快应用中心每次调用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");
}
}