Fun with Dot Grids (p5.js)

In this example below you will see how to do a Fun with Dot Grids (p5.js) with some HTML / CSS and Javascript

I wanted to make dots increase in size as the mouse gets close to them.

Thumbnail
This awesome code was written by Twinbee, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Twinbee ©
  • HTML
  • CSS
  • JavaScript
    <!-- Container Frame and ID for targeting p5 sketch insertion -->

<div class="container">
  <div id="sketch-holder"></div>
</div>

/*Downloaded from https://www.codeseek.co/Twinbee/fun-with-dot-grids-p5js-JpKPBN */
    // Setup the body for no scroll and a centered container
body {
  width: 100vw;
  height: 100vh;
  
  margin: 0;
  padding: 0;
  
  background: #222229;
  
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

// A nice Frame
.container {
  height: 500px;
  width: 500px;
  
  margin: 0 0 20px;
  
  background: azure;
  
  box-shadow: 0px 6px 20px #001;
  display: flex;
  justify-content: center;
  align-items: center;
}


/*Downloaded from https://www.codeseek.co/Twinbee/fun-with-dot-grids-p5js-JpKPBN */
    // Set Canvas height and width
let c = {
  "height": 400,
  "width": 400
}

// Setup Function for pixel clarity, canvas creation, and DOM insertion
function setup() {
  pixelDensity(2.0);
  let canvas = createCanvas(c.width, c.height);
  canvas.parent('sketch-holder');
}

// Draws the background and calls the function for drawing the dots
function draw() {
  clear();
  background(170, 200, 255);
  
  noStroke();
  fill(`rgba(255, 255, 255, .5)`);
  drawDots();
}

// i and j function as x and y when drawing the dot grid.  
function drawDots() {
  for(i=20; i<=c.height-20; i+=20) {
    for(j=20; j<=c.width-20; j+=20) {
      let dist = pythag(i, j);
      console.log(dist);
      
      let size = 2 + (20 * (20 / dist));
      if (size > 10) size = 10;
      ellipse(i, j, size, size);
    }
  }
}

// Grabs mouse position, checks if the mouse is off the screen (NaN) and calculates the distance from the mouse pointer and each dot using the pythagorean theorem.
function pythag(ellipseX, ellipseY) {
  let x = mouseX;
  let y = mouseY;
  
  if (x==NaN) {
    return 1;
  } else {
      let leg1 = Math.abs(x - ellipseX);
      let leg2 = Math.abs(y - ellipseY);
      let pyth = Math.pow(leg1, 2) + Math.pow(leg2, 2);
      return Math.sqrt(pyth);
  }
}

Comments