Javascript P5,在画布上绘制网格



我正在执行大学P5作业,正在努力理解我在网上找到的一些代码。我在下面包含了代码输出和实际代码的屏幕截图。我理解创建基本网格的逻辑,但我想知道是否有人可以向我解释它究竟是如何改变正方形大小的?

这是一个代码笔链接,可以看到它的工作原理: https://codepen.io/therealpamelahalpert/pen/rNaYrbP

'use strict';
var stepX = 60;
var stepY = 60;
var maxDistance = 600;
function setup() {
createCanvas(1240, 1748);
noStroke();
colorMode(HSB, 360, 100, 100);
}
function draw() {
clear();
for (var gridY = 0; gridY < height; gridY += stepY) {
for (var gridX = 0; gridX < width; gridX += stepX) {
//Creating the variable distanceBetweenTwoPoints which is getting the distance between 2 points on the canvas
distanceBetweenPoints = dist(mouseX, mouseY, gridX, gridY);
var diameter = distanceBetweenPoints / maxDistance * 60;
strokeWeight(4);
stroke(0,0,0);
rect(gridX, gridY, diameter, diameter);
}
}
}

代码的输出

dist()计算点之间的欧氏距离。
在这种情况下,它计算网格中当前位置(gridXgridY(和鼠标位置(mouseXmouseY(之间的距离:

distanceBetweenPoints = dist(mouseX, mouseY, gridX, gridY);

像元的大小取决于此距离。如果鼠标靠近单元格,则距离较短且尺寸较小。如果鼠标离单元格很远,则距离很大,单元格的大小也很大。
maxDistance的距离处,大小为60。低于maxDistance单元格较小,高于单元格较大:

var diameter = distanceBetweenPoints / maxDistance * 60;

请注意,您看不到单元格变得大于 60,因为它被稍后通过之后绘制的单元格绘制的单元格覆盖。
使用noFill来理解我的意思:

strokeWeight(4);
stroke(0,0,0);
noFill();
rect(gridX, gridY, diameter, diameter);

但是你可以通过使用min来摆脱它:

var diameter = min(1, distanceBetweenPoints / maxDistance) * 60;

请参阅示例,其中与左侧相比,右侧的大小是有限的:

var stepX = 60;
var stepY = 60;
var maxDistance = 200;
function setup() {
createCanvas(482, 482);
noStroke();
colorMode(HSB, 360, 100, 100);
}
function draw() {
clear();
for (var gridY = 0; gridY < height; gridY += stepY) {
for (var gridX = 0; gridX < width; gridX += stepX) {
//Creating the variable distanceBetweenTwoPoints which is getting the distance between 2 points on the canvas
distanceBetweenPoints = dist(mouseX, mouseY, gridX, gridY);
var diameter = distanceBetweenPoints / maxDistance * 60;
if (gridX >= 240)
diameter = min(1, distanceBetweenPoints / maxDistance) * 60;
strokeWeight(4);
stroke(0,0,0);
noFill();
rect(gridX, gridY, diameter, diameter);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

相关内容

  • 没有找到相关文章

最新更新