Hi, recently I was making my reactjs app and decided to use p5 canvas as background. Since I didn’t use p5 before, I found some code on internet and copy it to my app. Canvas (background) looks good on page first load, but I have some problems with windowResize event, which I added to code (as it should be added according to p5 documentation). I realize (by console.log()) that variables windowWidth and windowHeigth are changing on window resizing, event windowResize is triggered and even function draw() got called (by event). But this is where the problem arises. Although function draw() is called canvas is not redraw. Any suggestions?
Here is code:
let circles = [],
circle = {},
overlapping = false,
NumCircles = 40,
protection = 10000,
counter = 0;
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
function setup() {
let canvas = createCanvas(windowWidth, windowHeight);
// populate circles array
// brute force method continues until # of circles target is reached
// or until the protection value is reached
while (circles.length < NumCircles && counter < protection) {
circle = {
x: random(width),
y: random(height),
r: random(3, 15)
};
overlapping = false;
// check that it is not overlapping with any existing circle
// another brute force approach
for (var i = 0; i < circles.length; i++) {
var existing = circles[i];
var d = dist(circle.x, circle.y, existing.x, existing.y);
if (d < circle.r + existing.r) {
// They are overlapping
overlapping = true;
// do not add to array
break;
}
}
// add valid circles to array
if (!overlapping) {
circles.push(circle);
}
counter++;
}
}
function draw() {
background('rgb(250, 251, 234)');
noStroke();
fill('rgba(23, 174, 238, 0.3)');
for (let i = 0; i < circles.length; i++) {
ellipse(circles[i].x, circles[i].y, circles[i].r * 2, circles[i].r * 2);
}
}
And it is embedded in index.html:
<script src="https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.min.js"></script>
<script src="./canvas.js"></script>