javascript - 如何在 AngularJS 中设置范围之前等待图像加载?

标签 javascript html angularjs cytoscape.js

我正在使用 AngularJS 和 TypeScript。我正在使用 cytoscape 库以及 cytoscape-edgehandles 扩展和 AngularJS 的包装器 ngCytoscape。我正在尝试将图像添加到节点的悬停 handle 中,但是 cytoscape-edgehandles 2.7.1 中的 drawImage 方法的实现在绘制之前不会等待图像加载,因此会发生范围错误。

我试图在加载图像后为 cytoscape 图提供选项,但是 cytoscape 图希望这些选项立即可供使用。因此,我需要在将图像传递到图表之前加载图像。

在 Controller 的构造函数中:

this.$scope.ehOptions = this.GetEhOptions();

获取EhOptions方法:

protected GetEhOptions(): GraphModels.EhOptions {
    var options = new GraphModels.EhOptions;

    var img = new Image();
    img.width = 25;
    img.height = 25
    img.src = "../../Content/icons/ic_circle_add_24px.svg";
    options.handleImage = img;
    img.addEventListener('load', e => {
          return options;
    });
}

这会导致图表永远不会加载选项。如果我这样做,我会得到除图像之外的所有选项:

var options = new GraphModels.EhOptions;

var img = new Image();
img.width = 25;
img.height = 25
img.src = "../../Content/icons/ic_circle_add_24px.svg";

img.addEventListener('load', e => {
   options.handleImage = img;
});
return options;

有关handleIcon的cytoscape-edgehandles代码:

if(options().handleIcon){
    var icon = options().handleIcon;
    var width = icon.width*cy.zoom(), height = icon.height*cy.zoom();
    ctx.drawImage(icon, hx-(width/2), hy-(height/2), width, height);
}

如果改成这样,那么就可以了:

if (true) {
    var img = new Image();
    var width = 25 * cy.zoom();
    var height = 25 * cy.zoom();
    img.width = width;
    img.height = height
    img.src = "../../Content/icons/ic_circle_add_24px.svg";
    img.addEventListener('load', e => {
        ctx.drawImage(img, hx - (width/2), hy - (height/2), width, height)
    })
}

但是,我无法更改库代码。

希望大家有什么想法。谢谢!

最佳答案

创建 AngularJS promise :

protected GetEhOptions(): GraphModels.EhOptions {

    var deferred = $q.defer();
    var options = new GraphModels.EhOptions;           
    var img = new Image();

    img.width = 25;
    img.height = 25
    img.src = "../../Content/icons/ic_circle_add_24px.svg";
    options.handleImage = img;
    img.addEventListener('load', e => {
         ̶r̶e̶t̶u̶r̶n̶ ̶o̶p̶t̶i̶o̶n̶s̶;̶
         deferred.resolve(options);
    });
    img.addEventListener('error', e => {
         deferred.reject(e);
    });

    return deferred.promise;
}

然后从返回的 promise 中提取选项:

this.GetEhOptions().then(options => {
  this.$scope.ehOptions = options;
});

欲了解更多信息,请参阅

关于javascript - 如何在 AngularJS 中设置范围之前等待图像加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743870/

相关文章:

javascript - 我如何使用 angularjs 创建级联 md-select?

html - 为什么我不能从顶部删除边距/填充

java - 导航栏中的 wicket-bootstrap 面包屑

angularjs - 如何处理 angular-ui-router 和模板加载错误?

javascript - 下划线包含从头开始?

javascript - 通过表单在 Flask 上发布数据会出现 400 Bad Request

javascript - 如何使用 jQuery UI 范围 slider 更改变量的值

javascript - 在本地存储中存储压缩的 json 数据

javascript - 调用 karma 测试时未定义 Angular 错误

javascript - ng-if AngularJS中的日期比较不是年份