javascript - 如何在 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);
}
}
}
}
解决方案
您只需 1 个点即可绘制许多形状。beginShape
并endShape
包围形状的顶点。因此,您必须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>
推荐阅读
- javascript - Javascript警报不播放声音文件
- r - ifelse 条件:在前 n 位
- python - 高效的字符串匹配与 SQL 和 Python
- java - 如何在 Fragment 中使用 Google MapView?
- c# - 生成 100 多个 UI 游戏对象的最佳方式
- excel - Microsoft Excel - 将表格组合成一个“合并”表格
- ios - 比较对象领域 Swift
- python - SQLAlchemy 一对多关系映射/连接错误
- google-sheets - Google 表格单元格值不匹配
- mongodb - Mongodb:通过“_id”字段搜索嵌入文档