xxxxxxxxxx
47
// Welcome to the p5 editor, Vaqcoder!
// This editor is an excellent place for learning JavaScript.
// Here, you must use two functions, a setup, and a draw.
// Setup will always run once the page is loaded and
// after it is ran through, the draw loop will begin.
// The draw loop runs the code in the draw function over and over
// again.
// Press the play button to run your code.
// It will appear on the right.
let logo; // Here, I declare logo as a variable.
let x = 5; y = 5; // Here I make variables to hold the x
// and y positions of the image.
let s = 100; // Here, I create variables to hold the
// side length of the image.
let speed = 3; // This variable scales the velocity.
let vx = Math.random() + 0.5, // Here, I make variables to store
vy = Math.random() + 0.5; // a random velocity for the img.
// This 'preload' function is necessary for loading media.
// New media can be added by uploading to the project tree.
function preload() {
logo = loadImage("logo.png");
}
function setup() {
// Here I create a canvas of 400x400 pixels.
createCanvas(400, 400);
}
// Here is the 'draw loop'
function draw() {
background(51); // Clears canvas at beginning of each frame.
image(logo, x, y, s, s); // Draws image according to variables.
// Here, I change the velocity if the image hits an edge.
if (x <= 0 || x + s >= width) vx *= -1;
if (y <= 0 || y + s >= height) vy *= -1;
// Here, I update the position according to the velocity
// and I scale it by 'speed'.
x += vx * speed;
y += vy * speed;
}
// If you want to add more js files, add them via the
// project tree and include the script in the html.