我有一个问题,我试图解决多次,但我仍然失败。
我不确定问题是否属于“您不了解JavaScript基础知识”或存储桶“您不了解paper.js”。
背景
它看起来像这样:
var list_of_paperscopes = [];
for (var i = 0; i < number_of_desired_results; i++){
list_of_paperscopes.push( new paper.PaperScope() );
}
list_of_functions[1] = function (paperscope, callback) {
paperscope.setup(new paperscope.Size(500, 500));
// etc. etc.
// export paper result
paperscope.project.remove();
},
list_of_functions[2] = function (paperscope, callback) {
paperscope.setup(new paperscope.Size(300, 300));
// etc. etc.
// export paper result
paperscope.project.remove();
}
// ...
async.each(list_of_indices, function (index, asyncEachCallback) {
var paperscope = list_of_paperscopes.pop();
list_of_functions[index](paperscope, function (err, value) {
// do something
// etc etc.
问题
一般代码有效。 但不同的纸质项目相互干扰。原本应该在所有项目中的元素有时会累积在一个项目中而在所有项目中都缺乏。
问题
如何防止同时执行的纸质项目相互干扰?有没有一种方法可以让我使用async.each,还是我必须切换到连续缓慢的执行?
[编辑:]更新且更完整的代码示例
// This is still a toy example
// That is why some things may appear nonsensical when - in fact - they are required
var list_of_functions = [];
list_of_functions[0] = function (paperscope, callback) {
paperscope.setup(new paperscope.Size(300, 300));
// etc. etc.
// export paper result
paperscope.project.remove();
}
list_of_functions[1] = function (paperscope, callback) {
paperscope.setup(new paperscope.Size(300, 300));
// The following text will appear multiple times in the same paper project but not the others for THIS function with ID 1
var some_text = new paperscope.PointText({
point: [240, 190],
content: 'some text',
fillColor: 'black',
fontFamily: 'Courier New',
fontSize: 7,
justification: 'center'
});
// etc. etc.
// export paper result
paperscope.project.remove();
}
// This array determines how often we will call each function
var list_of_function_indices = [0, 1, 1, 1] // I want to execute function with ID 0 once, and the other function 3 times
async.each(list_of_function_indices, function (function_index, asyncEachCallback) {
// Generate a new PaperScope() object
var paperscope = new paper.PaperScope();
list_of_functions[function_index](paperscope, function (err, value) {
if (err) {
sails.log.error(err);
}
// always continue
asyncEachCallback();
});
}, function (err) {
if (err) {
sails.log.debug('A function failed...');
}
});
是不是paper.js一般不能异步执行?我不完全理解这一点:http://paperjs.org/reference/paperscope/#project
答案 0 :(得分:1)
感谢@Bergi和@NicholasKyriakides的帮助,我能够解决问题。
解决方案是提前生成PaperScope对象列表,如下所示:
var list_of_paperscope_objects = [];
for (var i = 0; i < number_of_desired_paperscopes; i++){
// Generate a new PaperScope() object
list_of_paperscope_objects.push( new paper.PaperScope() );
}
在我的每个异步函数中,我都可以创建并使用不同的papercope对象。为此,我将papercope对象列表以及键(索引)传递给每个函数。然后我可以做:
paperscopes[key].setup(new paper.Size(300, 200));
paperscopes[key].settings.insertItems = false;
var rect = new paperscopes[key].Path.Rectangle({
point: [0, 0],
size: [300, 300]
});
paperscopes[key].project.activeLayer.addChild(rect);
非常感谢评论者@Bergi和@NicholasKyriakides的帮助。