In-class excercises:
Changing colors of background and shapes:
let bgColor = 0;
let circleColor = 0;
let squareColor = 0;
//change colors on mouse click!
function setup() {
createCanvas(400, 400);
bgColor = random(255);
circleColor = random(255);
squareColor = random(255);
rectMode(CENTER);
}
function draw() {
background(bgColor);
fill(circleColor);
ellipse(0.33 * width, height * 0.5, 100, 100);
fill(squareColor);
rect(0.67 * width, height * 0.5, 100, 100);
if (mouseIsPressed) {
bgColor = color(random (255), random(255), random(255));
circleColor = color(random (255), random(255), random(255));
squareColor = color(random (255), random(255), random(255));
}
}
//function mousePressed() {
//bgColor = color(random (255), random(255), random(255));
//cicleColor = color(random (255), random(255), random(255));
//squareColor = color(random (255), random(255), random(255));
On p5js.org: Source
Rectangle appears....
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
if (mouseX > width/2) {
rect(100, 100, 200, 200);
}
ellipse(width/2, height/2, 50, 50);
}
On p5js.org: Source
Circle turns red/purple/blue on x-axis:
function setup() { createCanvas(400, 400); }
function draw() {
background(220);
if (mouseX < width * 0.333) { fill(255, 0, 0); }
else if (mouseX < width * 0.667) { fill (255, 0, 255); }
else { fill(0, 0, 255); }
ellipse(width/2, height/2, 300, 300); }
On p5js.org: Source
Click and drag circle + change color of circle:
let circleX = 100;
let circleY = 100;
let diameter = 150;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(255);
if (dist(circleX,circleY,mouseX,mouseY) < (diameter/2) && mouseIsPressed) {
fill(50);
circleX = mouseX;
circleY = mouseY;
}
ellipse(circleX, circleY, diameter, diameter);
}
On p5js.org: Source