moving a sketch from draw to setup - p5.js

Im playing around with the prime spiral code from Dan Shiffman:
https://www.youtube.com/watch?v=a35KWEjRvc0&t=716s&ab_channel=TheCodingTrain
I need to use this code as a background to another sketch, but due to the moving nature of the spiral its impossible that the spiral will not draw ontop of the other sketch, even with p5.layers.
I am therefore searching for a way to refactor this code into something that draw all the figures at once so use it as a background.
My idea is to create some kind of for loop in setup, but i am afraid its to big of nut to crack for me.
let x, y;
let step = 1;
let stepSize = 20;
let numSteps = 1;
let state = 0;
let turnCounter = 1;
let totalSteps;
let offset = 0;
function isPrime(value) {
if (value == 1) return false;
for (let i = 2; i <= sqrt(value); i++) {
if (value % i == 0) {
return false;
}
}
return true;
}
function setup() {
createCanvas(500, 500);
const cols = width / stepSize;
const rows = height / stepSize;
totalSteps = cols * rows;
x = width / 2;
y = height / 2;
background(0);
}
function draw() {
primeSpiral(20, 1)
primeSpiral(30, 200)
incrementStep();
noStroke();
}
function incrementStep()
{
switch (state) {
case 0:
x += stepSize;
break;
case 1:
y -= stepSize;
break;
case 2:
x -= stepSize;
break;
case 3:
y += stepSize;
break;
}
if (step % numSteps == 0) {
state = (state + 1) % 4;
turnCounter++;
if (turnCounter % 2 == 0) {
numSteps++;
}
}
step++;
if (step > totalSteps) {
noLoop();
}
}
function primeSpiral(offset, color){
if (!isPrime(step+offset)) {
//might put something here
} else {
let r = stepSize * 0.5;
fill(color, 99, 164);
push();
translate(x, y);
rotate(-PI / 4);
triangle(-r, +r, 0, -r, +r, +r);
pop();
}
}

You can move the code from draw() to the loop in setup(), here is example:
...
function setup() {
createCanvas(500, 500);
const cols = width / stepSize;
const rows = height / stepSize;
totalSteps = cols * rows;
x = width / 2;
y = height / 2;
background(0);
for (let i = 0; i<100; i++) { // 100 is the number of processed frames, you can change it as you need
primeSpiral(20, 1)
primeSpiral(30, 200)
incrementStep();
noStroke();
}
}
function draw() { // now draw is empty and you can place new code here
}
...

Related

p5js sketch slows down over time

I'm new to p5js and I'm trying to plot incoming x y data by drawing circles which initially expand and then shrink becoming 'fixed' , but the speed at which the circles expand slows down over time - and I can't work out why. I have one array which stores the animated expanding / shrinking circle and another which stores the final state of the fixed circle.
let circles = [];
let circlesStatic = [];
function setup() {
createCanvas(640, 480);
frameRate(60);
smooth();
// e1 = new Ellipse(320,240);
// e2 = new Ellipse(20,20);
background(0);
}
function mouseClicked() {
let e = new Ellipse(mouseX, mouseY);
circles.push(e);
}
function draw() {
for (let i = 0; i < circles.length; i++) {
circles[i].render();
}
for (let i = 0; i < circlesStatic.length; i += 2) {
// noFill();
fill('rgba(50,50,50, 0.1)');
strokeWeight(1);
stroke('rgba(100,100,100, 0.25)');
circle(circlesStatic[i], circlesStatic[i + 1], 20);
}
}
class Ellipse {
// constructor
constructor(x, y) {
this.x = x; // copy x argument value to the instance (this) x property
this.y = y; // copy x argument value to the instance (this) x property
// current size - continuously updated
this.size = 10;
// minimum size
this.minSize = 10;
// maximum size
this.maxSize = random(30, 35);
// change speed for size (how much will the size increase/decrease each frame)
this.sizeSpeed = 3;
// internal frameCount replacement
this.tick = 0;
// this.fill=(255,0,0);
}
render() {
// if the size is either too small, or too big, flip the size speed sign (if it was positive (growing) - make it negative (shrink) - and vice versa)
if (this.size < this.minSize || this.size > this.maxSize) {
this.sizeSpeed *= -1;
}
// increment the size with the size speed (be it positive or negative)
this.size += this.sizeSpeed;
console.log(this.sizeSpeed);
if (this.size < this.minSize) {
this.sizeSpeed = 0;
circlesStatic.push(this.x);
circlesStatic.push(this.y);
}
background(0);
// noStroke();
fill(200, 50, 0);
ellipse(this.x, this.y, this.size, this.size);
// this.tick++;
// this.size = map(sin(this.tick * this.sizeSpeed),-1.0,1.0,this.minSize,this.maxSize);
// fill(random(255), random(255), random(255));
// ellipse(this.x,this.y, this.size,this.size);
}
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>
The problem is that every time you render a circle it checks if it should become "static," and if it should it adds new values to circlesStatic. However, there is nothing to stop the animating circle to continue being rendered on subsequent frames. This results in massive numbers of entries being added to circlesStatic which means longer and longer render times. I've implemented one possible fix below. I also made it so that if you hold the shift key down you will see the previous behavior (watch the length of circlesStatic skyrocket after a few clicks). As soon as you release the shift key the fix will run and the number of entries in circlesStatic will plateau.
let circles = [];
let circlesStatic = [];
function setup() {
createCanvas(640, 480);
frameRate(60);
smooth();
// e1 = new Ellipse(320,240);
// e2 = new Ellipse(20,20);
textSize(16);
}
function mouseClicked() {
let e = new Ellipse(mouseX, mouseY);
circles.push(e);
}
function draw() {
background(0);
push();
noStroke();
fill('red')
text(`circles: ${circles.length}; circlesStatic: ${circlesStatic.length}`, 20, 20);
pop();
for (let i = 0; i < circles.length; i++) {
circles[i].render();
if (!keyIsDown(SHIFT)) {
if (circles[i].isStatic()) {
circles.splice(i, 1);
i--;
}
}
}
for (let i = 0; i < circlesStatic.length; i += 2) {
// noFill();
fill('rgba(50,50,50, 1)');
strokeWeight(1);
stroke('rgba(100,100,100, 1)');
circle(circlesStatic[i], circlesStatic[i + 1], 20);
}
}
class Ellipse {
// constructor
constructor(x, y) {
this.x = x; // copy x argument value to the instance (this) x property
this.y = y; // copy x argument value to the instance (this) x property
// current size - continuously updated
this.size = 10;
// minimum size
this.minSize = 10;
// maximum size
this.maxSize = random(30, 35);
// change speed for size (how much will the size increase/decrease each frame)
this.sizeSpeed = 3;
// internal frameCount replacement
this.tick = 0;
// this.fill=(255,0,0);
}
isStatic() {
return this.sizeSpeed === 0;
}
render() {
// if the size is either too small, or too big, flip the size speed sign (if it was positive (growing) - make it negative (shrink) - and vice versa)
if (this.size < this.minSize || this.size > this.maxSize) {
this.sizeSpeed *= -1;
}
// increment the size with the size speed (be it positive or negative)
this.size += this.sizeSpeed;
console.log(this.sizeSpeed);
if (this.size < this.minSize) {
this.sizeSpeed = 0;
circlesStatic.push(this.x);
circlesStatic.push(this.y);
}
// background(0);
// noStroke();
fill(200, 50, 0);
ellipse(this.x, this.y, this.size, this.size);
// this.tick++;
// this.size = map(sin(this.tick * this.sizeSpeed),-1.0,1.0,this.minSize,this.maxSize);
// fill(random(255), random(255), random(255));
// ellipse(this.x,this.y, this.size,this.size);
}
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.1/lib/p5.js"></script>

p5.js draw a rectangle at cursor position on mouse click

I have a very simple 9x9 grid. I know how to handle the rectangles on this grid. What I want is when I click on one of the grid rectangles, this rectangle should now be marked with a fill or border around it.
I can draw a rectangle, with a blue fill at exact the correct rectangle on the grid.
But with the next click on the grid, the new rectangle is drawn but the old rectangle is still there and will stay there. And so on.
My question is now, how can I paint always exact on rectangle at the click position?
Is maybe a class the right way?
Creating every time a new rectangle and destroy the old one?
var nullx = 140;
var nully = 50;
var breite = 65;
var hoehe = 65;
var pressed = false;
function setup() {
createCanvas(800, 1200);
}
function draw() {
//background(220);
noFill();
//strokeWeight(2);
sudokulines();
numberstorect();
if(pressed == true){
sqMark();
}
if (mousePressed == true){
console.log("click...")
sqMark();
}
}
function mousePressed(){
pressed = true;
}
function sqMark(){
var tempX;
var tempY;
//console.log(tempX,tempY);
tempX = (floor((mouseX - nullx) / breite) * breite) + nullx;
tempY = (floor((mouseY - nully) / hoehe) * hoehe) + nully;
console.log(tempX,tempY);
if (tempX > 139 && tempY > 49 ){
if (tempX < 661 && tempY < 571){
strokeWeight(0.7);
fill(0,0,255);
rect(tempX+2,tempY+2,breite-4,hoehe-4);
pressed = false;
}
}
}
function sudokulines(){
//The vertical lines
for (var i = 1; i <= 8; i++){
if (i == 3 || i == 6){
strokeWeight(3);
}else{
strokeWeight(1);
}
line(nullx + breite * i, nully, nullx + breite * i, nully+ 9*hoehe);
}
//The horizontal lines
for (var i = 1; i <= 8; i++){
if (i == 3 || i == 6){
strokeWeight(3);
}else{
strokeWeight(1);
}
//The big rectangle around
line(nullx , nully + hoehe * i, nullx + 9*breite, nully + hoehe * i);
}
strokeWeight(3);
rect(nullx,nully,9*breite,9*hoehe);
}
function numberstorect(){
textAlign(CENTER,CENTER);
fill(0);
textSize(breite/1.3);
text(2,nullx + breite/2, nully + hoehe/2);
}
It's important to understand that p5.js draws in immediate mode, so each element, once drawn, is not removable unless intentionally drawn over or cleared. This simplest solution to your specific problem is to simply save to location to be highlighted when the user presses the mouse, and then always clear the canvas and redraw everything (including the selected square) in the draw function. Because there's no animation, you can optimize this by disabling looping in your setup function, and then explicitly calling redraw when something happens that effects the display (i.e. the mouse is pressed).
var nullx = 140;
var nully = 50;
var breite = 65;
var hoehe = 65;
let selectedX = -1;
let selectedY = -1;
function setup() {
createCanvas(800, 1200);
// By default don't re draw every frame
noLoop();
}
function draw() {
background(255);
noFill();
//strokeWeight(2);
sudokulines();
numberstorect();
sqMark();
}
function mousePressed() {
// Set the selection
selectedX = (floor((mouseX - nullx) / breite) * breite) + nullx;
selectedY = (floor((mouseY - nully) / hoehe) * hoehe) + nully;
// Only redraw when something changes.
redraw();
}
function sqMark() {
if (selectedX > 139 && selectedY > 49) {
if (selectedX < 661 && selectedY < 571) {
strokeWeight(0.7);
fill(0, 0, 255);
rect(selectedX + 2, selectedY + 2, breite - 4, hoehe - 4);
pressed = false;
}
}
}
function sudokulines() {
//The vertical lines
for (var i = 1; i <= 8; i++) {
if (i == 3 || i == 6) {
strokeWeight(3);
} else {
strokeWeight(1);
}
line(nullx + breite * i, nully, nullx + breite * i, nully + 9 * hoehe);
}
//The horizontal lines
for (var i = 1; i <= 8; i++) {
if (i == 3 || i == 6) {
strokeWeight(3);
} else {
strokeWeight(1);
}
//The big rectangle around
line(nullx, nully + hoehe * i, nullx + 9 * breite, nully + hoehe * i);
}
strokeWeight(3);
rect(nullx, nully, 9 * breite, 9 * hoehe);
}
function numberstorect() {
textAlign(CENTER, CENTER);
fill(0);
textSize(breite / 1.3);
text(2, nullx + breite / 2, nully + hoehe / 2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

p5.js change object colour after X frames

I would like to change the fill colour of an object over time. Is there a way to change the fill colour of an object after X frames?
I am learning about constructors, and I am thinking that in the code's updateParticle function, after this.age counts to 'X', the fill colour of the ellipse could change.
'''
function Particle(x, y, xSpeed, ySpeed, size, colour) {
this.x = x;
this.y = y;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.size = size;
this.colour = colour;
this.age = 0;
this.drawParticle = function() {
fill(this.colour);
noStroke();
ellipse(this.x, this.y, this.size);
}
this.updateParticle = function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
this.age++;
}
}
function Emitter(x, y, xSpeed, ySpeed, size, colour) {
this.x = x;
this.y = y;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.size = size;
this.colour = colour;
this.particles = [];
this.startParticles = [];
this.lifetime = 0;
this.addParticle = function() {
var p = new Particle(random(this.x - 10, this.x + 10),
random(this.y - 10, this.y + 10),
random(this.xSpeed - 0.4, this.xSpeed + 0.4),
random(this.ySpeed - 5, this.ySpeed - 1),
random(this.size - 4, this.size + 40),
this.colour);
return p;
}
this.startEmitter = function(startParticles, lifetime) {
this.startParticles = startParticles;
this.lifetime = lifetime;
for (var i = 0; i < startParticles; i++) {
this.particles.push(this.addParticle());
}
}
this.updateParticles = function() {
var deadParticles = 0
for (var i = this.particles.length - 1; i >= 0; i--) {
this.particles[i].drawParticle();
this.particles[i].updateParticle();
if (this.particles[i].age > random(0, this.lifetime)) {
this.particles.splice(i, 1);
deadParticles++;
}
}
if (deadParticles > 0) {
for (var i = 0; i < deadParticles; i++) {
this.particles.push(this.addParticle());
}
}
}
}
var emit;
function setup() {
createCanvas(800, 600);
emit = new Emitter(width / 2, height - 100, 0, -1, 10, color(200, 0, 200, 50));
emit.startEmitter(600, 4000);
}
function draw() {
background(200);
emit.updateParticles();
}
'''
Well you could just:
if(frameCount % 30 == 0){ // % 30 is the remainder of num / 30, so 4 % 3 = 1, since 3 / 3 = 0 And 4 / 3 = 3.33
fill("lime") // these are just preset colors in p5.js AND css lime == rgb(0,255,0)
} else {
fill('darkred')
}
or you could also do it with for example a switch statement: using background for no reason
switch(MY_frameCount){
case 1:
background('blue')
break
case 2:
background("darkgreen")
break
case 376:
background(crimson)
// break
}
MY_frameCount ++
or:
if(Math.random() < 0.1){
fill(Math.random() * 255, Math.random() * 255, Math.random() * 255)
} // this should on average fill with random color every 10 frames

P5.js Creating a fading curve on a grid

I've made a square grid on top of the canvas and also a cruve (that is meant to have a fading trail). I made them seperately and tried combining them so the curve would appear on top of the grid. However, it doesn't show the curve.
I've commented out the grid so it's easier to see the curve.
How do I get this to work?
var cols = 10;
var rows = 10;
var t = 0;
var particleArray = [];
function setup() {
createCanvas(600, 600);
background(0);
fill(100);
rect(0, 0, 550, 550, 25);
}
// blue grid
function draw() {
/*for (var c = 0; c < cols; c++) {
for (var r = 0; r < rows; r++) {
var XO = 25 + c * 50;
var YO = 25 + r * 50;
stroke(0);
fill(100,149,237);
rect(XO, YO, 50, 50);
noLoop();
// :(
}
}
*/
//curve
y = width / 2 + 270 * sin(3 * t + PI / 2) - 25;
x = height / 2 + 270 * sin(1 * t) - 25;
particleArray.push(new Particle(x, y, t));
for (i=0; i<particleArray.length; i++) {
particleArray[i].show(t);
}
if (particleArray.length > 700) {
particleArray.shift();
}
t += .01;
}
function Particle(x, y, t) {
this.x = x;
this.y = y;
this.t = t;
this.show = function(currentT) {
var _ratio = t / currentT;
_alpha = map(_ratio, 0, 1, 0, 255); //points will fade out as time elaps
fill(255, 255, 255, _alpha);
ellipse(x, y, 5, 5);
}
}
I don't know if this was intentional but you called noLoop() function where you're drawing the grid. If you comment that out it works.

Clearing text but keeping existing graphics

I am making this random little sketch where you can click and drop coins and there is a count of how many coins you have in the top left.
The problem I am running into is, whenever you run this you will notice that the amount label just continuously stacks on top of itself whenever it updates. I have read other posts that say that we need to redraw the background to clear the text but when I do this, it also removes any coins that have been generated on the canvas. How can I update this to keep the coins visible but remove and redraw the amount?
var moneyCount = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
background(100);
}
function draw() {
if (mouseIsPressed){
dropCoins();
displayCount();
}
}
function displayCount() {
textSize(80);
text('$' + moneyCount, 80, 80);
}
function dropCoins() {
var maxSize = 40;
var xLoc = mouseX;
var yLoc = mouseY;
makeStacks(xLoc, yLoc, maxSize);
}
function makeStacks(x, y, size){
fill(255,215,0);
ellipse(x, y, size);
for (i = 0; i < size; i++){
let r1 = random(100);
let r2 = random(100);
if (r1 < 50){
x = x + 2
} else {
x = x - 2;
}
if (r2 < 50){
y = y + 2;
} else {
y = y - 2;
}
moneyCount++;
ellipse(x, y, size);
}
}
You have a couple of options available:
You store where the coins are so you can redraw them after you clear the background
You use multiple "layers" using createGraphics() so you can clear the background, but not the coins PGraphics
For option 1 you can do something like this:
var moneyCount = 0;
var coins = [];
function setup() {
createCanvas(windowWidth, windowHeight);
textSize(80);
}
function draw() {
background(100);
if (mouseIsPressed){
dropCoins();
}
displayCoins();
displayCount();
}
function displayCount() {
text('$' + moneyCount, 80, 80);
}
function dropCoins() {
var maxSize = 40;
var xLoc = mouseX;
var yLoc = mouseY;
makeStacks(xLoc, yLoc, maxSize);
}
function makeStacks(x, y, size){
for (i = 0; i < size; i++){
let r1 = random(100);
let r2 = random(100);
if (r1 < 50){
x = x + 2
} else {
x = x - 2;
}
if (r2 < 50){
y = y + 2;
} else {
y = y - 2;
}
moneyCount++;
coins.push({x:x,y:y,size:size});
}
}
function displayCoins(){
fill(255,215,0);
for(var i = 0 ; i < coins.length; i++){
ellipse(coins[i].x,coins[i].y,coins[i].size);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
The idea is you would initialise an array to store the data you would need to redraw the coins (x,y, and size (if it varies)).
Bare in mind the more coins you'd add, the more memory you'd use.
If you simply need the rendered image and don't need the coin position data, option 2 will be more efficient.
For option 2 the main idea, as you can see in the documentation, is that you can have another graphics layer to draw into. Once initialised simply use dot notion on the instance and use the typical p5 drawing calls on it. To render it use image()
Here's a demo for the PGraphics option:
var moneyCount = 0;
var coinsLayer;
function setup() {
createCanvas(windowWidth, windowHeight);
textSize(80);
coinsLayer = createGraphics(windowWidth, windowHeight);
}
function draw() {
background(100);
// render coins layer
image(coinsLayer,0,0);
if (mouseIsPressed){
dropCoins(coinsLayer);
}
displayCount();
}
function displayCount() {
text('$' + moneyCount, 80, 80);
}
function dropCoins(coinsLayer) {
var maxSize = 40;
var xLoc = mouseX;
var yLoc = mouseY;
makeStacks(coinsLayer, xLoc, yLoc, maxSize);
}
function makeStacks(layer, x, y, size){
layer.fill(255,215,0);
layer.ellipse(x, y, size);
for (i = 0; i < size; i++){
let r1 = random(100);
let r2 = random(100);
if (r1 < 50){
x = x + 2
} else {
x = x - 2;
}
if (r2 < 50){
y = y + 2;
} else {
y = y - 2;
}
moneyCount++;
layer.ellipse(x, y, size);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

Resources