You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Processing的setup()中添加beginRecord()和endRecord()致草图异常

问题分析与解决

核心问题

你的SVG导出为空有两个关键原因:

  • checkOverlap函数逻辑错误,导致图形根本没被正确绘制
  • 输出目录可能不存在,导致Processing无法写入SVG文件

1. 修复重叠检测逻辑

原checkOverlap遍历了整个数组,但第i次循环时,k > i的数组元素都是默认值0,会错误触发重叠判断,且反复重置绘制逻辑。正确做法是只检查当前点之前已记录的坐标:

void checkOverlap(int xx, int yy, int jj) {
  tooClose = false;
  // 仅检查已保存的前jj个坐标
  for (int k = 0; k < jj; k++) {
    if (xx == coordx[k] && yy == coordy[k]) {
      tooClose = true;
      break; // 找到重叠直接跳出循环
    }
  }
  // 仅在不重叠时绘制图形
  if (!tooClose) {
    noStroke();
    fill(0);
    ellipse(xx, yy, sz, sz);
  }
}

2. 确保输出目录存在

你的导出路径是"output/filenameZ####.svg",如果sketch文件夹下没有output子目录,Processing无法创建文件,会生成0字节空文件。解决方法:

  • 手动在sketch目录下创建output文件夹
  • 或直接导出到根目录,将路径改为"filenameZ####.svg"

3. 优化细节

  • runWalker里的float move = int(random(0, 4));可简化为int move = int(random(4));
  • 边界判断可改用三元运算符简化代码,不影响功能

修复后的完整代码

int counter = 1000;
int[] coordx = new int[counter];
int[] coordy = new int[counter];

int x;
int y;

int sz = 10;

boolean tooClose;

void setup() {
  size(500, 500);
  rectMode(CENTER);
  
  // 从屏幕中心开始
  x = width/2;
  y = height/2;
  
  // 确保output目录存在,或改为直接输出到根目录
  beginRecord(SVG, "output/filenameZ####.svg");

  background(255);
  noStroke();

  for (int i = 0; i < counter; i++) {
    runWalker();
    checkOverlap(x, y, i);
    coordx[i] = x;
    coordy[i] = y;
  }

  endRecord();
}

void draw() {
}

void checkOverlap(int xx, int yy, int jj) {
  tooClose = false;
  // 仅检查已记录的前jj个坐标
  for (int k = 0; k < jj; k++) {
    if (xx == coordx[k] && yy == coordy[k]) {
      tooClose = true;
      break;
    }
  }
  if (!tooClose) {
    fill(0);
    ellipse(xx, yy, sz, sz);
  }
}

void runWalker() {
  int move = int(random(4));

  if (move == 0) {
    x += sz;
  } else if (move == 1) {
    y += sz;
  } else if (move == 2) {
    x -= sz;
  } else {
    y -= sz;
  }

  // 边界循环处理
  x = (x < 0) ? width : x;
  x = (x > width) ? 0 : x;
  y = (y < 0) ? height : y;
  y = (y > height) ? 0 : y;
}

验证步骤

  1. 运行修复后的代码,会在指定目录生成SVG文件
  2. 打开SVG文件,可看到随机游走且无重叠的圆点
  3. 导入Inkscape后即可用Axidraw正常打印

内容的提问来源于stack exchange,提问作者samseurynck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 13:32:05