Possible to restrict mouseDragged to canvas in instance mode?

Hi frens,
I want to register the mouseDragged Function to a canvas in instance mode (within a react component).
But mouseDragged is not available (only mousePressed and mouseClicked…).

Is there a workaround to check if the mouse is dragged inside the canvas?

var sketch = function( p ) {

  p.setup = function() {
    var cnv = p.createCanvas(700, 410);
    cnv.mouseDragged(doStuff);
  };

  p.draw = function() {
    p.rect(50, 50,50,50);
  };

  function doStuff() {
    p.background(p.random(255));
  }
};

var myp5 = new p5(sketch);

Log:
TypeError: cnv.mouseDragged is not a function

Thanks
Res

Hi @res56,

mouseDragged is not a function on the canvas, it’s a function on the p5 instance:

var sketch = function( p ) {

  p.mouseDragged = function() {
    doStuff();
  }

  // ...
};

var myp5 = new p5(sketch);

Hi @josephh

thanks for your reply. This works indeed but then the event is fired outside the canvas…

Thanks

1 Like

Maybe you can set a variable mouseDown (that you would create) and then in mousePressed set it to true and in mouseReleased set it to false

Then evaluate it: when it’s true, we drag

1 Like

Yes - try this

let mySketch = function (p) {
    mouseOverCanvas = false;
    backCol = 128;

    p.setup = function () {
        let p5canvas = p.createCanvas(300, 200);
        p5canvas.canvas.addEventListener('mouseenter', (e) => { mouseOverCanvas = true; });
        p5canvas.canvas.addEventListener('mouseout', (e) => { mouseOverCanvas = false; });
    }

    p.draw = function () {
        p.background(backCol);
    }

    p.mouseDragged = function () {
        if (mouseOverCanvas)
            backCol = p.floor(p.random(256));
    }

}

new p5(mySketch);
2 Likes

@Chrisir && @quark

works perfect! Thanks

1 Like