1

我正在为大学完成 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);
        }
    }
}

代码的输出

4

1 回答 1

1

dist()计算点之间的欧几里得距离
在这种情况下,它计算网格中的当前位置 ( gridX, gridY) 和鼠标位置( mouseX, ) 之间的距离mouseY

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>

于 2020-01-04T08:54:28.123 回答