Drawing from mousePressed?

Ok, so I'm sure there is a stupidly easy answer and I'm totally embarrassed to ask this...

I want to draw a circle when the mouse is clicked at mouseX, mouseY but it doesn't seem to work. Can you explain why?

function setup() {
    createCanvas(600, 600);
}

function draw() {
    background(200);
}

function mousePressed() {
    ellipse(mouseX, mouseY, 180);
}

I have been trying to google and search the forums for an answer. I did find a KahnAcademy answer which is pretty much the same code but they're using processing.js.

Answers

  • edited March 2017

    Recall that draw() is called back at about 60 FPS by default: L-)
    http://p5js.org/reference/#/p5/draw

    So in your sketch, the canvas is being cleared by background() @ 60 FPS! @-)

    Try out this sketch below at https://OpenProcessing.org/sketch/create,
    and see if it's more likely what you wish: B-)

    function setup() {
      createCanvas(600, 600);
      frameRate(60);
    }
    
    function draw() {
      background(200);
      mouseIsPressed && ellipse(mouseX, mouseY, width/3);
    }
    
  • ... but they're using processing.js.

    It's a spinoff of Pjs! :>

  • Wow didn't know you can use the operator AND like that.

    Interesting that mousePressed works but mousePressed and mouseClicked doesn't.

    I want the circle to be permanently on the canvas after the click though.

  • Just use your original sketch. But move background() to setup(). *-:)

  • Oh man, sorry I wasn't being specific enough, I'd like to have the circle be a new circle each time it changes position.

  • Answer ✓
    function setup() {
      createCanvas(600, 600).mousePressed(redraw);
      fill('yellow').noLoop();
      mouseX = mouseY = -width;
    }
    
    function draw() {
      background(200);
      ellipse(mouseX, mouseY, width/3);
    }
    
  • edited March 2017

    Thats it! Thanks!

      createCanvas(600, 600).mousePressed(redraw);   fill('yellow').noLoop();

    mouseX = mouseY = -width;

    These lines confuse me though. Having a period after canvas, (redraw) and noLoop?

    I thought setup runs only once? If you could explain these that would be great.

  • edited March 2017 Answer ✓

    Method p5.Element::mousePressed() calls back the passed function argument every time the canvas is clicked at: http://p5js.org/reference/#/p5.Element/mousePressed

    As the callback for it, I've picked redraw(): http://p5js.org/reference/#/p5/redraw

    The noLoop() is there. But it's being chained invoked by the p5 object returned by fill(). :ar!

  • Thanks so much! I will study and research that code!

Sign In or Register to comment.