1
votes

it's been years since I coded anything, and now I need to pick up p5.js. As practice I was trying to make a simple drawing program - I want my program to draw in black by default, and switch the color to red when I click on the red rectangle in the corner of the screen. I had the following very sloppy code (I know the mouse-press doesn't exactly line up with the red rectangle, the 'drawing' mechanism isn't the best, etc. I'm just messing around with it atm)

function setup() {
	createCanvas(600, 600);
	fill ('red'); 
  	rect(570,20,5,5);
  //creates red rectangle at top right corner of screen

}
var color = 0;
function mousePressed(){
	if ( mouseX > 570) {
  		if( mouseY > 20){
  			color = 4;
  			ellipse (10,20,50,50);
  		}
  		
  	}
}
function draw() {
	
  stroke(color);
  if (mouseIsPressed) {
  	ellipse(mouseX, mouseY, 1, 1)
  	//creates colored dot when mouse is pressed
  } 
}

function keyTyped(){
	if (key === 'c'){
		clear();
	}
}

If I don't use the 'color' variable and instead just set the stroke to 0, I can draw in black well enough. And the mousePressed function seems to work - when I press the rectangle, it draws the ellipse that I put in to test. However, I can't seem to reference var 'color' in my draw function - it's probably a silly problem, but I admit to being stumped! What am I doing wrong?

1

1 Answers

1
votes

You have to be careful when naming variables. Specifically, you shouldn't name them the same thing as existing functions!

From the Processing.js help articles:

One of the powerful features of JavaScript is its dynamic, typeless nature. Where typed languages like Java, and therefore Processing, can reuse names without fear of ambiguity (e.g., method overloading), Processing.js cannot. Without getting into the inner-workings of JavaScript, the best advice for Processing developers is to not use function/class/etc. names from Processing as variable names. For example, a variable named line might seem reasonable, but it will cause issues with the similarly named line() function built-into Processing and Processing.js.

Processing.js is JavaScript, so functions can be stored in variables. For example, the color variable is the color() function! So when you create your own color variable, you're overwriting that, so you lose the ability to call the color() function.

The simplest fix is to just change the name of your color variable to something like myColor.