我正在使用 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/