在 canvas.ToBlob() 异步函数之外访问 blob 值

编程入门 行业动态 更新时间:2024-10-28 15:29:02
本文介绍了在 canvas.ToBlob() 异步函数之外访问 blob 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HTMLCanvas 元素,该元素返回 async toBlob() 函数之外的 blob 对象.此函数不返回输出值,因此我尝试在外部声明一个变量并通过命令访问它.

I'm working with HTMLCanvas element that return the blob object outside of the async toBlob() function. This function doesn't return an output value, so I'm trying to declare a variable outside and access it through the command.

我如何在这种情况下使用 JS Promise?

How I can use JS Promise for this scenario?

var myblob;
            canvas.toBlob(function(blob) {                         
                              myblob = blob;
                              console.log("inside " + myblob); // getting value after the console outside
                           })
 console.log( "outside " + myblob); // getting undefined   

推荐答案

你可以使用 Promise 构造函数,将 Blob 实例传递给 resolve(),在.then()

You can use Promise constructor, pass Blob instance to resolve(), access Promise value at .then()

function getCanvasBlob(canvas) {
  return new Promise(function(resolve, reject) {
    canvas.toBlob(function(blob) {
      resolve(blob)
    })
  })
}

var canvasBlob = getCanvasBlob(canvas);

canvasBlob.then(function(blob) {
  // do stuff with blob
}, function(err) {
  console.log(err)
});

这篇关于在 canvas.ToBlob() 异步函数之外访问 blob 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-30 02:45:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/768605.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   canvas   ToBlob   blob

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!