Search code examples
p5.jsml5.js

Showing and hiding images in p5 sketch


I'm drawing images on the canvas when noseX position (detected with webcam and ml5 poseNet model) hits a certain part of the canvas (eg noseX > 50). However I would like the image that is drawn to disappear again when the noseX position is not in the canvas area that triggers the appearance of that certain image. Same story goes for the noseX position indicator (black ellipse), it eventually draws a path/line where the noseX position has been but I just want it to be a dot that follows the noseX without leaving a trace. Here's my p5 sketch: https://editor.p5js.org/saskiasmith/sketches/Z57YsGRsH Many thanks!


Solution

  • If you add another call of the background() function at the beginning of every draw() loop then it will clear the canvas every frame and get the effect you wanted

    If you think about it, you're outputting these images and circles onto the screen but never telling the screen to clear, and that's what calling background() every frame will do

    function draw() {
      background(245); // <-- Here is the new background call
      push();
      translate(width, 100);
      image(webcam, 0, 0, 0, 0);
      pop()
        
      let d = dist(noseX, noseY, eyelX, eyelY);
      let pX = (noseX);
      let pY = (noseY);
      ...