copy function does not recognize image on another canvas in p5js

I'm trying to make 'slitscan' effects.
I set 2 canvases. One on the right is for source image, and another is for scan effect.
When i tried it with text function it works perfectly, however with an image, the copy function gives me an error message.

the error message

This is the p5 code I wrote

let a1, a2;
let cv1, cv2;
let dy = 0;

let s1 = function(p) {
  p.setup = () => {
    cv1 = p.createCanvas(300, 300);
    p.background(150);
    cv1.position(0, 0);
  }

  p.draw = () => {
    p.copy(cv2, 0, dy, 400, 1, 0, dy, 400, 1);
    
    if (dy > cv2.height) {
      dy = 0;
    } else {
      dy += 1;
    } 
  }
}
a1 = new p5(s1);

let s2 = function(p) {
  let img;

  p.preload = () => {
    img = p.loadImage('https://pbs.twimg.com/profile_images/635910989498724356/uY4bc8q2.jpg');
  }

  p.setup = () => {
    cv2 = p.createCanvas(300, 300);
    cv2.position(300, 0);
  }

  p.draw = () => {
    p.background(30);
    p.imageMode(p.CENTER);
    p.image(img, p.mouseX, p.mouseY);
  }
}
a2 = new p5(s2);

In addition, if you have a better idea to make multi-canvas or any suggestion about my code, please leave a comment. Thanks,

1 answer

  • answered 2020-10-29 22:52 Malte

    In your s1 sketch, you try to do stuff with the canvas cv2. Yet this canvas is only created later in your sketch.

    To fix it, just change the order of your two sketches, i.e., call a1 = new p5(s1); after a2 = new p5(s2); (it doesn't matter when you define s1 and s2, only when you instantiate them).

    See, for example, this p5 editor sketch.