'P5.js Trying to Update shape "Fill" with the pixels of underlying image

Hi i want that on the sketch, the circles that are created have the "Fill" constantly updated with what the background image is. At the moment the "Fill" value is just captured on the first instance. In a way that the moving circles make the image Visible. Hope this is understandable.

https://editor.p5js.org/archaonpash/sketches/tvyMIoJ2i



Solution 1:[1]

You need to get the color of the image in the show method every time a new circle is drawn:

show(){
    noStroke();
    let c = img.get(this.x,this.y);
    fill(c);
    ellipse(this.x,this.y,this.size)
}

let img;
let bubbles = [];

function preload(){
    img = loadImage("https://picsum.photos/500/500")
}

class Bubble{
  ////WHAT DOES IT MEAN TO BE A BUBBLE
  constructor(x,y,size){
    this.x = x;
    this.y = y;
    this.size = size;
  }
  //// MOVE IS THE POSITION VARIATION OVER TIME IN DRAW
  move(){
    this.x = this.x +random(-5,5);
    this.y = this.y +random(-5,1);
  }
  /////SHOW IS THE WAY THIS IS SHOWED ON CANVAS(it also gives the x,y, that changes according to "MOVE")
  show(img){
    noStroke();
    let c = img.get(this.x,this.y);
    fill(c);
    ellipse(this.x,this.y,this.size)
  }
}

function setup() {  
     createCanvas(img.width, img.height);
     background(0);
     for (let initloop = 0; initloop < 1000; initloop++){
         let x = random(width);
         let y = random(height);
         let size = 10
         bubbles[initloop] = new Bubble(x,y,size)
     }
}

function draw() {
     img.loadPixels();
     for ( let initdraw = 0; initdraw < bubbles.length; initdraw++){
         bubbles[initdraw].show(img);
         bubbles[initdraw].move();
     }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1