I'm trying to loop through my current canvas in p5js after having added geometric information with the draw function.
So I've declared a function getCanvas() to try to loop through it, and get the pixels copied to a variable, but it doesn't seem to work. I get this error:
Cannot read property of undefined. Check the line number in error and make sure the variable which is being operated is not undefined.
Can someone shed some light on this problem? The idea is to draw several things and save the canvas by pressing 'p', bind it to a variable so that it can be inserted to an array. This is my code:
let canvas;
let img;
function setup() {
let img = createImage(300, 300);
img.loadPixels();
canvas = createCanvas(windowWidth, windowHeight);
background(220);
...
}
function draw() {
//code that draws what I need successfully
...
}
function getCanvas(image){
let h, k;
// fill with random colors
for (h = 0; h < canvas.height; h ) {
for (k = 0; k < canvas.width; k ) {
image.pixels[h][k] = get(h, k);
}
}
}
function keyPressed() {
if (key === 'p'){
getCanvas(img);
img.updatePixels();
image(img, 0, 0);
}
CodePudding user response:
Right now, img
is defined in the scope of the setup
function, so you cannot access it outside of there.
You need to move it's declaration outside of setup
into the global scope to be able to use it in your other functions:
let img;
function setup() {
img = createImage(300, 300);
img.loadPixels();
canvas = createCanvas(windowWidth, windowHeight);
background(220);
// ...
}