Please help me explaining this code logic

Hi y’all, I am very new to P5.js.
I am learning the dist() function of P5js ,and there is this code exercise that I have to Create a spotlight when the cursor is moved. I have a hard time understand the logic behind this code. Especially the part of size= (size/canvas_dist) *70;
Can you help me understand this part?
Thank you so much!

The code is here:

// Stores diagnal distance across the canvas
let canvas_dist;

function setup() {
  createCanvas(windowWidth, windowHeight);
  canvas_dist = dist(0,0,width,height); 

function draw() {
  background(255, 40);

  // Nested for loops tp draw a grid of ellipses
  for (let i = 0; i <= width; i += 15) {
    for (let j = 0; j <= height; j += 15) {
      // TODO: Calculate the distance between mouse position and each ellipse's position
      let size = dist (mouseX, mouseY, i,j);
      // TODO: Reassign size to be proportional to the size of the canvas
      size= (size/canvas_dist) *70;
      // Try uncommenting the second fill function below:
     // fill(j, i,size, 10 );
      // TODO: set width and height of ellipse to size variable
      ellipse(i, j, size, size);
1 Like

size represents the distance between mouse and current cell in the grid

This value gets adjusted and the result is again put into the variable “size”.

It is then used as a radius when you draw the ellipse/ cell of the grid.

How does it get modified?

canvas_dist is a global variable that gets defined in setup () - it’s the length of the window’s diagonal.

So our formula says: divide the distance to mouse by
window diagonal and multiply by 70.

This means the bigger your window, the smaller one
cell. The comments explain a lot here, in this case
that this line is a placeholder and is still to do.

So you have to design the line. How do you want
the ellipse to change when is closer or more far away?

You can modify the formula and use map() command for example

1 Like

Hello @Jiji,

I assume you have read the p5.js references related to each element of your code.

console.log() is useful to examine what the value of variables are; it will slow things down so only use in developing code and you can comment these to only observe the ones you are focusing on. Modify as required to suit you.

Do you understand this code below?
I split the line you are asking about into steps.

let canvas_dist;

function setup() {
  createCanvas(windowWidth, windowHeight);
  canvas_dist = dist(0,0,width,height); 
  console.log(windowWidth, windowHeight, width, height, canvas_dist);

function draw() 
  background(255, 40);
  let sz0 = dist (0, 0, mouseX, mouseY)
  console.log(sz0, mouseY, sz0);
  let sz1 = sz0/canvas_dist;
  let sz2 = sz1*50;           
  fill(255, 0, 0)
  ellipse(mouseX, mouseY, sz2, sz2)
  console.log(mouseX, mouseY, sz2);

What is a ratio?