xxxxxxxxxx
120
// In this example we are loading a background
// image and then draw text and shapes on top.
//
// make changes to the numbers in the code below
// and see what happens. Add some movement to
// text or shapes. How to? Use frameCount instead
// of a static number or use the sin or tan function.
//
// take screenshot(s) and screen-recordings when
// you are happy with changes and outcomes
// rendered to the canvas.
// what is backgroundImage and font?
// backgroundImage and font are 2 variables which
// we will use to store an image and a font in memory
// from where we can read it later.
let backgroundImage;
let font;
function preload() {
// first we need to preload media
// like images and fonts
backgroundImage = loadImage("image.jpg");
font = loadFont("Inconsolata.otf");
}
function setup() {
// then, lets set the size of our canvas
createCanvas(540, 720);
// set variable font to the font
// we just preloaded
textFont(font);
}
function draw() {
background(255,10)
// display the image as background first
// @make-changes-here
// you may want to disable the image below by
// using // before image, this is called
// uncommenting out code
image(backgroundImage, 0, 0, width, height);
// now prepare and write some
// text on top of the background.
noStroke();
fill(0, 0, 255);
textSize(50);
text("Conditional", 30, 100);
text("Design", 30, 150);
// add some shape(s)
// @make-changes-here
// the following code makes use of variables and
// if-else conditionals which activate the movement
// of shapes when the mouse and/or keys are pressed.
// give it a try and try to figure out how this work
// by changing numbers in the following.
let speed = 0.05;
let range = 100;
if (mouseIsPressed) {
range = 100;
speed = 0.35;
}
// a is a variable. assigned to a is a value
// which is calculated from the sine-function
// and 3 more variables. frameCount is provided
// by p5js, speed and range are defined above and
// are different when the mouse is pressed or not.
let a = sin(frameCount * speed) * range;
// we will use the value of a below to make
// shapes move.
// retangle
fill(200, 200, 200);
if (mouseIsPressed) {
fill(0,0,255);
rect(400 + a, 200, 100, 300);
} else {
rect(400, 200 + a, 100, 300);
}
//triangle in the back
fill(0, 0, 255);
if (keyIsPressed) {
triangle(-a, 400 - a, 200 - a, 200, 350, 500);
} else {
fill(200,200,200);
triangle(100, 400, 200, 200, 350, 500);
}
// triangle in the front
if (keyIsPressed){
fill(0,0,255);
triangle(100, 500, 500, 500, 300, 600);
}
else{
fill(200,200,200);
}
}
function mouseMoved() {
// when we move the mouse, we want
// to read canvas coordinates. We can do so by
// using the console.log() command and writing
// the mouse coordinates to the console window.
console.log("x:", mouseX, "y:", mouseY);
}