Creating p5.js Projects on Pickcode
p5.js is a popular Javascript library for making visual designs and animations. With Pickcode's website editor, it's easy to get started. First, create a new HTML/CSS/JS website project in the sandbox, then we'll edit our files.
index.html
In our HTML file, we load p5.js in a script tag, and we link our sketch.js
file (we'll set that up next)
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/p5@1.9.0/lib/p5.min.js"></script>
</head>
<body></body>
<script src="./sketch.js"></script>
</html>
sketch.js
In your project, open the file sidebar (with the hamburger button in the top left), click "Add...", and select "Text file". Call your file sketch.js
. In sketch.js
, we can write our actual p5 code. Below is code to make a bouncing ball animation.
let x, y;
let xspeed, yspeed;
let radius = 25;
function setup() {
createCanvas(400, 400);
x = width / 2;
y = height / 2;
xspeed = 5;
yspeed = 3;
}
function draw() {
background(220, 200, 0);
// Move the ball
x += xspeed;
y += yspeed;
// Bounce off walls
if (x > width - radius || x < radius) {
xspeed *= -1;
}
if (y > height - radius || y < radius) {
yspeed *= -1;
}
// Draw the ball
fill(0, 0, 0);
noStroke();
ellipse(x, y, radius * 2, radius * 2);
}
Once your code is added, you should see your animation. Happy coding!