在 PaperJS 中加载外部 JSON 文件

Load external JSON file in PaperJS

我认为这会很简单:

project.importJSON('structures.json')

不幸的是,这给了我:

JSON Parse error: Unexpected identifier "structures"

这个 "structures" 必须来自 JSON 文件 structures.json 本身,它看起来像这样:

{
    "structures": [
        {"name":"shed",     "width": 4, "height": 3,    "depth": 5},
        {"name": "house",   "width": 6, "height": 7,    "depth": 5},
        {"name": "factory", "width": 4, "height": 3.5,  "depth": 6.5, 
                                                        "depth_sub_1": 5.5, 
                                                        "depth_sub_2": 4.5 }
    ]   
}

关于如何使这项工作有任何想法吗?我不想为此使用 jQuery。

编辑

所以在我看来,使用 importJSON 只能在 JSON 是一个实际的 Paper 对象时才有效。同样的错误不断发生。

还有什么选择?我想要 我的外部 'structural' 数据 基本上 一个 JavaScript 文件中。我应该使用常规路线吗?

我的 html 看起来像这样:

<head>
  <script type="text/javascript" src="../../assets/javascript/paper-full.js"></script>
  <script type="text/paperscript" src="I/a_view_on_my_structures.js" canvas="phase-I"></script>
</head>

<body>
  <canvas id="phase-I" resize="true"></canvas>
</body>

您应该将数据字符串化。

var structures = {
    "structures": [
        {"name":"shed",     "width": 4, "height": 3,    "depth": 5},
        {"name": "house",   "width": 6, "height": 7,    "depth": 5},
        {"name": "factory", "width": 4, "height": 3.5,  "depth": 6.5, 
                                                        "depth_sub_1": 5.5, 
                                                        "depth_sub_2": 4.5 }
    ]   
}
project.importJSON(JSON.stringify(structures))

如果您 json 数据在不同的文件中,您应该先阅读该文件

这就是您读取文件的方式

同步

var client = new XMLHttpRequest();
  client.open('GET', 'path/to/your/file', false);
  client.onreadystatechange = function() {
    //your data is in client.responseText
    console.log(client.responseText);
  }
  client.send(null);

异步

var client = new XMLHttpRequest();
  client.open('GET', 'path/to/your/file');
  client.onreadystatechange = function() {
    //your data is in client.responseText
    console.log(client.responseText);
  }
  client.send();

请注意,当您执行此操作时,您不需要对数据进行字符串化,因为您将其作为文本阅读,因此您只需将 client.responseText 内容传递给 importJSON函数