首页 > 解决方案 > 如何在 JS 中用 p5 绘制一个不完美的圆

问题描述

我创建了一个脚本来计算 JS 中的圆的坐标。我正在使用 p5.js 绘制圆圈,但是当我运行脚本时没有任何反应。我认为这与我绘制顶点的方式有关?

var xValues = [];
var yValues = [];

function setup() {
  createCanvas(400, 400);
  background(220);
  crookedCircle(10, 10, 10, 10);
}

function draw() {}

function crookedCircle(radius, steps, centerX, centerY) {
  for (var i = 0; i < steps; i++) {
    xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));
    yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));
    for (let x = 0; x < xValues.length; x++) {
      for (let y = 0; y < yValues.length; y++) {
        //console.log("x: "+xValues[x] + " y: "+yValues[y])
        beginShape();
        vertex(xValues[x] + random(-10, 10), yValues[y]) + random(-10, 10);
        endShape(CLOSE);
      }
    }
  }
}

标签: javascriptgeometryp5.js

解决方案


您只需 1 个点即可绘制许多形状。beginShapeendShape包围形状的顶点。因此,您必须beginShape在循环之前和循环endShape之后调用:

function crookedCircle(radius, steps, centerX, centerY) {
    beginShape();
    for (var i = 0; i < steps; i++) {
        // [...]
    }
    endShape(CLOSE);  
}

如果要绘制 1 个圆圈,一个循环就足够了:

var xValues = [];
var yValues = [];

function setup() {
    createCanvas(400, 400);
}

function draw() {
    background(220);
    fill(255)
    crookedCircle(100, 90, 120, 120);
}

function crookedCircle(radius, steps, centerX, centerY) {
    for (var i = 0; i < steps; i++) {
        xValues[i] = centerX + radius * Math.cos(2 * Math.PI * i / steps);
        yValues[i] = centerY + radius * Math.sin(2 * Math.PI * i / steps);
    }
    beginShape();
    for(let i = 0; i < steps; i ++) {
        vertex(xValues[i] + random(-2, 2), yValues[i] + random(-2, 2));
    }
    endShape(CLOSE);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>


推荐阅读