代码之家  ›  专栏  ›  技术社区  ›  buckybuck

p5js中的xml文件出错(“语法错误:应为;但找到了表”)

  •  0
  • buckybuck  · 技术社区  · 7 年前

    使用p5。js我正在尝试用随机颜色绘制12个正方形,当按下鼠标时可以重新绘制-我使用下面的代码完成了这一操作:

    function setup() {
    //build-up canvas w/ 12 squares
    createCanvas(800, 600);
    
    for (var y=0; y<600;y+=200) {
      for (var x=0; x<800; x+=200) {
        fill(random(255), random(255), random(255));
        rect(x, y, 200, 200)
      }
    }
    function touchStarted() {
    // figure-out where to redraw square
      var qX = (mouseX - (mouseX % 200)) / 200
      var qY = (mouseY - (mouseY % 200)) / 200
    
     fill(random(255), random(255), random(255));
     rect(qX*200, qY*200, 200, 200);
    }
    

    但现在我正试图将数据保存在一个包含此类内容的xml文件中:

    <build>
        <square id="0" posx="0", posy="0">30</square>
        <square id="1" posx="200", posy="0">60</square>
    

    我试着用它作为参考( https://p5js.org/reference/#/p5.XML ) :

    var xml;
    
    function preload() {
      xml = loadXML("assets/data.xml");
    }
    
    function setup() {
      // build-up canvas w/ 12 squares
      createCanvas(800, 600);
    
      var children = xml.getChildren("build");
    
      for (var i=0; i < children.length; i++) {
        var xpos = children[i].getNum("posx");
        var ypos = children[i].getNum("posy");
        var coul = children[i].getContent();
        fill(coul);
        rect(xpos, ypos, 200, 200);
      }
    

    但我只得到了错误“SyntaxError:应为;但找到了表”,所以我真的迷路了。。。

    谢谢你的帮助!

    1 回复  |  直到 7 年前
        1
  •  1
  •   MercyDude    7 年前

    尝试以下操作: I'v更改了 var children = xml.getChildren("build"); var children = xml.getChildren("square");

    var xml;
    
    function preload() {
      xml = loadXML("assets/data.xml");
    }
    
    function setup() {
      // build-up canvas w/ 12 squares
      createCanvas(800, 600);
    
      var children = xml.getChildren("square"); // <----- CHANGED IT FROM BUILD TO SQUARE
    
      for (var i=0; i < children.length; i++) {
        var xpos = children[i].getNum("posx");
        var ypos = children[i].getNum("posy");
        var coul = children[i].getContent();
        fill(coul);
        rect(xpos, ypos, 200, 200);
      }
    

    也不要忘记关闭xml文件内部的。 应该是这样的:

    <build>
    <square id="0" posx="0", posy="0">30</square>
    <square id="1" posx="200", posy="0">60</square>
    </build>