mouseWheel and other callback functions not working in Instance Mode

#1

After converting my code into instance mode, all the callback functions I had in place are not working anymore: for example mouseWheel, mousePressed, windowResized and so on.
Should those functions reside inside the instance class scope or outside?
Thank you for any help!

#2

Can you please post a MCVE?

Inside.

#3

Solved thanks, I assigned the functions to the sketch object passed inside the p5 constructor and then they worked. Something like sketch.windowResized() { }

#4

Or something like this: sketch.windowResized = function () { } :wink:

p5js.org/examples/instance-mode-instantiation.html

1 Like
#5

Yes actually that’s the correct solution, thanks

#6

Would you be willing to post an example of this? Struggling to get mouseWheel working in instance mode.

#7

http://p5js.SketchPad.cc/sp/pad/view/ro.C9V0wpmLEMeNC4/latest

#8

Thank you. Still seem to be having issues getting the variable to be recognized within the instance.


var canvasDiv = document.getElementById('container');
var width = canvasDiv.offsetWidth;
var height = canvasDiv.offsetHeight;
var pos = 25;

var s = function( p ) {
 
    
  p.setup = function() {
    p.createCanvas(width, height);
  };

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

 
};

var myp5 = new p5(s,"container");

function mouseWheel(event) {
  print(event.delta);
  //move the square according to the vertical scroll amount
  pos += event.delta;
  //uncomment to block page scrolling
  //return false;
}

window.onresize = function () {
    location.reload();
}```
#9

The code from my link is in “global” mode, not “instance”! :globe_with_meridians:

Obviously, a global-scoped mouseWheel() won’t be recognized as a callback function by a sketch in “Instance” mode! :telephone_receiver:

Just follow the same approach you’re already doing for callbacks setup() & draw(): :bulb:

function mouseWheel(event) { :arrow_right: p.mouseWheel = function (event) {

#10

Perfect. Thank you. Leaving the final example here.

var canvasDiv = document.getElementById('container');
var width = canvasDiv.offsetWidth;
var height = canvasDiv.offsetHeight;
var pos = 25;

var s = function( p ) {
 
    
  p.setup = function() {
  
    p.createCanvas(width, height);
  };

  p.draw = function() {
  	p.background(0);
    p.rect(pos,100,50,50);
  };

  p.mouseWheel = function (event) {
  p.print(event.delta);
  //move the square according to the vertical scroll amount
  pos += event.delta;
  //uncomment to block page scrolling
  //return false;
}
 
};

var myp5 = new p5(s,"container");



window.onresize = function () {
    location.reload();
}