JS如何在onload中return
发布日期:2021-09-12 09:57:52
浏览次数:99
分类:技术文章
本文共 2000 字,大约阅读时间需要 6 分钟。
很多情况下我们希望在onload事件中返回一个值,例如我们在图片加载完以后返回一些图片的信息
const image = new Image(); image.onload = function () { ... return ... }; image.src = url;
如果我们直接返回的话都知道是return不出来的,我之前是向onload函数中传入回调函数,执行回调函数传入想要的值,但是有了Promise对象我们可以更简单的解决这个问题,直接就可以在then中取得我们想要的值,可以举一反三。
function loadImageAsync(url) { return new Promise(function(resolve, reject) { const image = new Image(); image.onload = function() { resolve(image); }; image.onerror = function() { reject(new Error('Could not load image at ' + url)); }; image.src = url; });}
下面是我自己做的一个完整的实例,构建一个util文件夹,index.ts代码如下
/** * 将路径图片转换为base64 * @param url 图片的静态路径 * @param coef 图片质量系数 */export const base64TransformByURL = function (url: string, coef:number = 1){ function getBase64Image(img: HTMLImageElement) { let canvas: HTMLCanvasElement = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; let ctx: any = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height); let ext: string = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase(); let base64: string = canvas.toDataURL("image/" + ext, coef).split(',')[1]; return base64; } return new Promise(function (resolve, reject){ const image: HTMLImageElement = new Image(); image.onload = function () { resolve(getBase64Image(image)); }; image.src = url; }) }/** * 将上传的文件转换成base64 返回,目前仅支持单文件 * @param file */export const base64TransformByFile = async function(file: any){ return new Promise(function (resolve, reject) { const oReader: FileReader = new FileReader(); oReader.onload = async function (e: any) { resolve(await base64TransformByURL(e.target.result)) } oReader.readAsDataURL(file); })}
这样在调用的时候只需要
public async handleFileChange(event: any) { const r = await base64TransformByFile(event.currentTarget.files[0]); this.props.onFileChange(r);}
转载地址:https://blog.csdn.net/weixin_38361925/article/details/95099838 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年04月12日 05时22分46秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
EfficientDet训练自己的数据集实现抽烟检测
2019-04-26
【工具篇】10分钟快速上手git与github
2019-04-26
【开发篇】10分钟快速上手spring boot
2019-04-26
【开发篇】10分钟快速spring boot+react前后端分离
2019-04-26
【开发篇】10分钟快速上手spring boot+mybatis增删改查
2019-04-26
【Leetcode刷题篇】leetcode203 移除链表元素
2019-04-26
【Leetcode刷题篇】leetcode108 将有序数组转换为二叉搜索树
2019-04-26
【Leetcode刷题篇】leetcoe109 有序链表转换二叉搜索树
2019-04-26
【Leetcode刷题篇】leetcode938 二叉搜索树的范围和
2019-04-26
【Leetcode刷题篇】leetcode235 二叉搜索树的最近公共祖先
2019-04-26
【Leetcode刷题篇】leetcode236 二叉树的最近公共祖先
2019-04-26
【Leetcode刷题篇】leetcode230 二叉搜索树中第K小的元素
2019-04-26
【Leetcode刷题篇】leetcode173 二叉搜索树迭代器
2019-04-26
【Leetcode刷题篇】leetcode99 恢复二叉搜索树
2019-04-26
【Leetcode刷题篇】leetcode451根据字符出现频率排序
2019-04-26
【Leetcode刷题篇】leetcode703 数据流中的第k大元素
2019-04-26
【Leetcode刷题篇】leetcode378 有序矩阵中第K小的元素
2019-04-26
【Leetcode刷题篇】前K个高频元素
2019-04-26
【Leetcode刷题篇】leetcode373 查找和最小的K对数字
2019-04-26
【Leetcode刷题篇】leetcode367 有效的完全平方数
2019-04-26