I created a program to change the greyscale value of the background by tracking the mouseX
position and mapping it unto the greyscale range, so that when I move the mouse left and right the color changes from black to white respectively.
I want to track the greyscale value as I move the mouse about, by calling the print()
command upon clicking the mouse using function mousePressed()
When I run the program, the background color changes exactly as intended, meaning that the variable z
is being calculated just fine, yet upon mouse click nothing prints and an error message is received: "p5.js says: There's an error due to "z" not being defined in the current scope."
WHAT I KNOW:
- tracking
mouseX
by printing it to console withprint()
, upon mouse click usingfunction mousePressed()
works fine, as I had used it successfully in a different program I made. even just switching the variablez
inside theprint()
command tomouseX
works.
WHAT ELSE I TRIED:
- I created a new variable, set its value to
z
and tried printing the new variable... didnt work. - I mapped the size of the canvas to the greyscale range (0-255) manually by division of the two numbers, and multiplied that by
mouseX
variable name -ratio
. when I tried to printratio
the same problem occurred.
WHAT DO I WANT AN ANSWER TO?:
- Why does this error occur upon calling either the mapped variable, and the manually calculated one?
- How can I make this idea of clicking at any given mouse position, to receive the current greyscale value work? (preferably without calling any straightforward function like
background.color
or something) - This is my first question on this website and I tried to make it as readable as possible. I would like to receive some feedback on my question, was it easy to understand? was it too descriptive? and whatever else you might see appropriate and helpful for further question uploading.
CODE: https://editor.p5js.org/KaliPali/sketches/uVx_T9kH5
var frame = { //this is used to save the canvas size and use it
x: 600,
y: 400
}
function setup() {
createCanvas(frame.x, frame.y);
}
function draw() {
var z = map(mouseX, 0, frame.x, 0, 255) // first attempt. doesnt work
//var ratio = mouseX*255/frame.x; //manual mapping attempt. doesnt work
background(z);
rectMode(CENTER)
rect(mouseX,200,10,60)
}
function mousePressed() {
print('greyscale value is: ' + z)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>