PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 25, 2022

[FIXED] How to store current canvas in array?

 October 25, 2022     canvas, oop, p5.js     No comments   

Issue

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);
  }


Solution

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);

  // ...
}


Answered By - Samathingamajig
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing