adding multiple objects in p5.js - javascript

I have a little bit of javascript,
which is calling from the processing/p5.js library a number of tools.
// Spring drawing constants for top bar
let springHeight = 19,
left,
right,
maxHeight = 300,
minHeight = 0,
over = false,
move = false;
// Spring simulation constants
let M = 0.8, // Mass
K = 0.2, // Spring constant
D = 0.92, // Damping
R = 180; // Rest position
// Spring simulation variables
let ps = R, // Position
vs = 0.0, // Velocity
as = 0, // Acceleration
f = 0; // Force
function setup() {
createCanvas(710, 400);
rectMode(CORNERS);
// rectMode(CORNER);
c = color('rgb(255,233,234)');
fill(c);
noStroke();
left = width / 2 - 400;
right = width / 2 + 400;
}
function draw() {
background(102);
updateSpring();
drawWire();
}
function drawWire() {
rect(left, ps + 10, right, ps + springHeight);
// rect(left, ps + 10, right, ps + springHeight);
}
function updateSpring() {
// Update the spring position
if ( !move ) {
f = -K * ( ps - R ); // f=-ky
as = f / M; // Set the acceleration, f=ma == a=f/m
vs = D * (vs + as); // Set the velocity
ps = ps + vs; // Updated position
}
if (abs(vs) < 0.1) {
vs = 0.0;
}
// Test if mouse if over the top bar
if (mouseX > left && mouseX < right && mouseY > ps && mouseY < ps + springHeight) {
over = true;
} else {
over = false;
}
// Set and constrain the position of top bar
if (move) {
ps = mouseY - springHeight / 2;
ps = constrain(ps, minHeight, maxHeight);
}
}
function mousePressed() {
if (over) {
move = true;
}
}
function mouseReleased() {
move = false;
}
the javascript file, when run in my html, will create a single, pleasantly springy string:
what would be the best way to change this code so that multiple strings are produced,
perhaps spaced vertically by n pixels?
I have tried simply replicating the code block, but can not seem to be getting this right!

If you just want to draw multiple strings then use a for loop. Compute the y coordinate of the top of the string dependent on the control variable (i) of the loop. e.g. y = ps + springDist * i;:
e.g. 3 strings:
let springDist = 40.0;
function drawWire() {
for (let i = 0; i < 3; ++i) {
let y = ps + springDist * i;
rect(left, y, right, y+springHeight);
}
}
Of course you have to check if the mouse is over any of the strings and to state (move_i) which string is "touched":
let move_i = 0;
function updateSpring() {
// [...]
// Test if mouse if over the top bar
over = false;
for (let i = 0; i < 3; ++i) {
let y = ps + springDist * i;
if (mouseX > left && mouseX < right && mouseY > y && mouseY < y + springHeight) {
over = true;
move_i = i;
}
}
// Set and constrain the position of top bar
if (move) {
ps = mouseY - springHeight / 2 - move_i * springDist;
ps = constrain(ps, minHeight, maxHeight);
}
}
If you want to move each string individually, then you have to create a list of objects:
let strings = [];
function setup() {
// [...]
for (let i = 0; i < 3; ++i) {
let ps = R + springDist * i;
strings.push({ps : ps, vs : 0.0, as : 0, f : 0, R : ps})
}
}
Draw the objects:
function drawWire() {
for (let i = 0; i < strings.length; ++i) {
let y = strings[i].ps;
rect(left, y, right, y+springHeight);
}
}
Update the objects in a loop and move the individual object which is dragged (move_i):
function updateSpring() {
// Update the spring position
for (let i = 0; i < strings.length; ++i) {
let st = strings[i];
if ( i != move_i || !move ) {
st.f = -K * ( st.ps - st.R ); // f=-ky
st.as = st.f / M; // Set the acceleration, f=ma == a=f/m
st.vs = D * (st.vs + st.as); // Set the velocity
st.ps = st.ps + st.vs; // Updated position
}
if (abs(st.vs) < 0.1) {
st.vs = 0.0;
}
}
// Test if mouse if over the top bar
over = false;
for (let i = 0; i < strings.length; ++i) {
let y = strings[i].ps
if (mouseX > left && mouseX < right && mouseY > y && mouseY < y + springHeight) {
over = true;
move_i = i;
}
}
// Set and constrain the position of top bar
if (move) {
strings[move_i].ps = mouseY - springHeight / 2;
strings[move_i].ps = constrain(strings[move_i].ps, minHeight, maxHeight);
}
}
See the example:
// Spring drawing constants for top bar
let springHeight = 19,
springDist = 40,
left,
right,
maxHeight = 300,
minHeight = 0,
over = false,
move = false;
move_i = 0;
// Spring simulation constants
let M = 0.8, // Mass
K = 0.2, // Spring constant
D = 0.92, // Damping
R = 180; // Rest position
// Spring simulation variables
let strings = [];
function setup() {
createCanvas(710, 400);
rectMode(CORNERS);
// rectMode(CORNER);
c = color('rgb(255,233,234)');
fill(c);
noStroke();
left = width / 2 - 400;
right = width / 2 + 400;
for (let i = 0; i < 3; ++i) {
let ps = R + springDist * i;
strings.push({ps : ps, vs : 0.0, as : 0, f : 0, R : ps})
}
}
function draw() {
background(102);
updateSpring();
drawWire();
}
function drawWire() {
for (let i = 0; i < strings.length; ++i) {
let y = strings[i].ps;
rect(left, y, right, y+springHeight);
}
}
function updateSpring() {
// Update the spring position
for (let i = 0; i < strings.length; ++i) {
let st = strings[i];
if ( i != move_i || !move ) {
st.f = -K * ( st.ps - st.R ); // f=-ky
st.as = st.f / M; // Set the acceleration, f=ma == a=f/m
st.vs = D * (st.vs + st.as); // Set the velocity
st.ps = st.ps + st.vs; // Updated position
}
if (abs(st.vs) < 0.1) {
st.vs = 0.0;
}
}
// Test if mouse if over the top bar
over = false;
for (let i = 0; i < strings.length; ++i) {
let y = strings[i].ps
if (mouseX > left && mouseX < right && mouseY > y && mouseY < y + springHeight) {
over = true;
move_i = i;
}
}
// Set and constrain the position of top bar
if (move) {
strings[move_i].ps = mouseY - springHeight / 2;
strings[move_i].ps = constrain(strings[move_i].ps, minHeight, maxHeight);
}
}
function mousePressed() {
if (over) {
move = true;
}
}
function mouseReleased() {
move = false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

Related

Why does this code create arrays filled with the same repeating value?

I have been trying to write a simulator using the HTML5 Canvas. I have the following code to generate equipotential lines for electric fields.
function drawEqLines(charges) {
// don't bother if there aren't any charges
if (charges.length == 0) return;
// the Charge class contains the charge of the charge as well as its x and y coordinates
var fieldFilled = [];
for (var i = 0; i < 10; i++) {
fieldFilled.push([]);
for (var j = 0; j < 10; j++) {
fieldFilled[i].push(false);
}
}
var calculatedFields = [];
var maxForce = 0;
for (var i = 0; i < fieldFilled.length; i++) {
var direction = 1;
for (var jj=0; jj < fieldFilled[i].length; jj++) {
if (!fieldFilled[i][jj]) {
//create a path here
//Iterate at most 2 times in case the surface gets out of the area
for (var circleTimes = 0; circleTimes < 3; circleTimes+=2) {
//Define the center of the current block as a starting point of the surface
/*
horizontalBlock and verticalBlock are the width and height of the canvas divided into 10 different sections.
_BlockHalf is half of one of the blocks
*/
var curX = i * this.horizontalBlock + this.horizontalBlockHalf;
var curY = jj * this.verticalBlock + this.verticalBlockHalf;
// Point is a class that contains an x and y value
var curPt = new Point(curX, curY);
var direction = 1 - circleTimes;
var dots = [];
dots.push(curPt);
//Superposition the fields from all charges, and get the resulting force vector
var dirX = 0;
var dirY = 0;
var totalForce = 0;
for (var j = 0; j < charges.length; j++) {
var distX = curPt.x - charges[j].x;
var distY = curPt.y - charges[j].y;
var distanceSq = distX * distX + distY * distY;
var force = charges[j].charge / distanceSq;
var distanceFactor = force / Math.sqrt(distanceSq);
//Measure the initial force in order to match the equipotential surface points
totalForce += force;
dirX += distX * distanceFactor;
dirY += distY * distanceFactor;
}
//Maximum 2000 dots per surface line
var times = 2000;
while (times-- > 0) {
var dirTotal = Math.sqrt(dirX * dirX + dirY * dirY);
var stepX = dirX / dirTotal;
var stepY = dirY / dirTotal;
//The equipotential surface moves normal to the force vector
curPt.x = curPt.x + direction * 6 * stepY;
curPt.y = curPt.y - direction * 6 * stepX;
/*
*
* ***********************LOG LINE HERE***********************************
*
*/
// this prints out unique values
console.log(curPt.x + ", " + curPt.y);
//Correct the exact point a bit to match the initial force as near it can
var minForceIndex = -1;
var minForceDiff = 0;
var minDirX = 0;
var minDirY = 0;
var minCurX = 0;
var minCurY = 0;
curPt.x -= 3 * stepX;
curPt.y -= 3 * stepY;
for (var pointIndex = 0; pointIndex < 7; pointIndex++, curPt.x += stepX, curPt.y += stepY) {
dirX = 0;
dirY = 0;
var forceSum = 0;
for (var j = 0; j < charges.length; j++) {
var distX = curPt.x - charges[j].x;
var distY = curPt.y - charges[j].y;
var distanceSq = distX ** 2 + distY ** 2;
var force = charges[j].charge / distanceSq;
var distanceFactor = force / Math.sqrt(distanceSq);
//Measure the initial force in order to match the equipotential surface points
forceSum += force;
dirX += distX * distanceFactor;
dirY += distY * distanceFactor;
}
var forceDiff = Math.abs(forceSum - totalForce);
if (minForceIndex == -1 || forceDiff < minForceDiff) {
minForceIndex = pointIndex;
minForceDiff = forceDiff;
minDirX = dirX;
minDirY = dirY;
minCurX = curPt.x;
minCurY = curPt.y;
} else {
break;
}
}
//Set the corrected equipotential point
curPt.x = minCurX;
curPt.y = minCurY;
dirX = minDirX;
dirY = minDirY;
//Mark the containing block as filled with a surface line.
var indI = parseInt(curPt.x / this.horizontalBlock);
var indJ = parseInt(curPt.y / this.verticalBlock);
if (indI >= 0 && indI < fieldFilled.length) {
if (indJ >= 0 && indJ < fieldFilled[indI].length) {
fieldFilled[indI][indJ] = true;
}
}
//Add the dot to the line (was commented out when I added the other log)
dots.push(curPt);
if (dots.length > 5) {
//If got to the begining, a full circle has been made, terminate further iterations
if (indI == i && indJ == jj) {
distX = dots[0].x - curPt.x;
distY = dots[0].y - curPt.y;
if (distX * distX + distY * distY <= 49) {
dots.push(new Point(dots[0].x, dots[0].y));
times = 0;
circleTimes = 3;
}
}
//If got out of the area, terminate further iterations for this turn.
if (curPt.x < 0 || curPt.x > this.canvas.width || curPt.y < 0 || curPt.y > this.canvas.height) {
times = 0;
}
}
}
calculatedFields.push([totalForce, dots]);
maxForce = Math.max(maxForce, Math.abs(totalForce));
}
}
}
}
console.log(calculatedFields);
// draw the lines from the arrays of dots here...
}
The result of this code is an array that looks like this:
[
[
0.000007927962725256215,
[
// as you can see, these points are all the same
{x: 114.16365557137308, y: 402.6147544331975},
{x: 114.16365557137308, y: 402.6147544331975},
{x: 114.16365557137308, y: 402.6147544331975},
{x: 114.16365557137308, y: 402.6147544331975},
// etc...
]
],
[
0.000006140401131528559,
[
{x: -1.0201768243546043, y: 323.28955989370445},
{x: -1.0201768243546043, y: 323.28955989370445},
{x: -1.0201768243546043, y: 323.28955989370445},
{x: -1.0201768243546043, y: 323.28955989370445},
// etc...
]
]
]
These points should be unique, however, it seems to just generate the same point over and over again. For some reason, it does decide to stop after a reasonable number of iterations, as if it is doing the calculations correctly but just putting the same point into the array anyway.
Why is this happening? How can I fix it?
Update: Here are the classes that I am using:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class Charge {
constructor(charge, x, y) {
this.charge = charge;
this.x = x;
this.y = y;
}
}
Also, the charges array is fine, because I use it in a similar method which does work correctly. An example for this would be:
[
{charge: 6, x: 50, y: 50},
{charge: -4, x: 70, y: 90.5},
// etc...
]
Update 2:
I have tried adding the log line indicated in the above code, which prints out only unique values. However, even if I try pushing the point to the array here it still results in the same issue.
Update 3:
Added this runnable snippet:
const height = 400; // for example
const width = 600; // also for example
const horizontalBlock = width / 10;
const verticalBlock = height / 10;
const horizontalBlockHalf = horizontalBlock / 2;
const verticalBlockHalf = verticalBlock / 2;
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
function drawEqLines(charges) {
// don't bother if there aren't any charges
if (charges.length == 0) return;
// the Charge class contains the charge of the charge as well as its x and y coordinates
var fieldFilled = [];
for (var i = 0; i < 10; i++) {
fieldFilled.push([]);
for (var j = 0; j < 10; j++) {
fieldFilled[i].push(false);
}
}
var calculatedFields = [];
var maxForce = 0;
for (var i = 0; i < fieldFilled.length; i++) {
var direction = 1;
for (var jj=0; jj < fieldFilled[i].length; jj++) {
if (!fieldFilled[i][jj]) {
//create a path here
//Iterate at most 2 times in case the surface gets out of the area
for (var circleTimes = 0; circleTimes < 3; circleTimes+=2) {
//Define the center of the current block as a starting point of the surface
/*
horizontalBlock and verticalBlock are the width and height of the canvas divided into 10 different sections.
_BlockHalf is half of one of the blocks
*/
var curX = i * horizontalBlock + horizontalBlockHalf;
var curY = jj * verticalBlock + verticalBlockHalf;
// Point is a class that contains an x and y value
var curPt = new Point(curX, curY);
var direction = 1 - circleTimes;
var dots = [];
dots.push(curPt);
//Superposition the fields from all charges, and get the resulting force vector
var dirX = 0;
var dirY = 0;
var totalForce = 0;
for (var j = 0; j < charges.length; j++) {
var distX = curPt.x - charges[j].x;
var distY = curPt.y - charges[j].y;
var distanceSq = distX * distX + distY * distY;
var force = charges[j].charge / distanceSq;
var distanceFactor = force / Math.sqrt(distanceSq);
//Measure the initial force in order to match the equipotential surface points
totalForce += force;
dirX += distX * distanceFactor;
dirY += distY * distanceFactor;
}
//Maximum 2000 dots per surface line
var times = 2000;
while (times-- > 0) {
var dirTotal = Math.sqrt(dirX * dirX + dirY * dirY);
var stepX = dirX / dirTotal;
var stepY = dirY / dirTotal;
//The equipotential surface moves normal to the force vector
curPt.x = curPt.x + direction * 6 * stepY;
curPt.y = curPt.y - direction * 6 * stepX;
/*
*
* ***********************LOG LINE HERE***********************************
*
*/
// this prints out unique values
console.log(curPt.x + ", " + curPt.y);
//Correct the exact point a bit to match the initial force as near it can
var minForceIndex = -1;
var minForceDiff = 0;
var minDirX = 0;
var minDirY = 0;
var minCurX = 0;
var minCurY = 0;
curPt.x -= 3 * stepX;
curPt.y -= 3 * stepY;
for (var pointIndex = 0; pointIndex < 7; pointIndex++, curPt.x += stepX, curPt.y += stepY) {
dirX = 0;
dirY = 0;
var forceSum = 0;
for (var j = 0; j < charges.length; j++) {
var distX = curPt.x - charges[j].x;
var distY = curPt.y - charges[j].y;
var distanceSq = distX ** 2 + distY ** 2;
var force = charges[j].charge / distanceSq;
var distanceFactor = force / Math.sqrt(distanceSq);
//Measure the initial force in order to match the equipotential surface points
forceSum += force;
dirX += distX * distanceFactor;
dirY += distY * distanceFactor;
}
var forceDiff = Math.abs(forceSum - totalForce);
if (minForceIndex == -1 || forceDiff < minForceDiff) {
minForceIndex = pointIndex;
minForceDiff = forceDiff;
minDirX = dirX;
minDirY = dirY;
minCurX = curPt.x;
minCurY = curPt.y;
} else {
break;
}
}
//Set the corrected equipotential point
curPt.x = minCurX;
curPt.y = minCurY;
dirX = minDirX;
dirY = minDirY;
//Mark the containing block as filled with a surface line.
var indI = parseInt(curPt.x / this.horizontalBlock);
var indJ = parseInt(curPt.y / this.verticalBlock);
if (indI >= 0 && indI < fieldFilled.length) {
if (indJ >= 0 && indJ < fieldFilled[indI].length) {
fieldFilled[indI][indJ] = true;
}
}
//Add the dot to the line (was commented out when I added the other log)
dots.push(curPt);
if (dots.length > 5) {
//If got to the begining, a full circle has been made, terminate further iterations
if (indI == i && indJ == jj) {
distX = dots[0].x - curPt.x;
distY = dots[0].y - curPt.y;
if (distX * distX + distY * distY <= 49) {
dots.push(new Point(dots[0].x, dots[0].y));
times = 0;
circleTimes = 3;
}
}
//If got out of the area, terminate further iterations for this turn.
if (curPt.x < 0 || curPt.x > width || curPt.y < 0 || curPt.y > height) {
times = 0;
}
}
}
calculatedFields.push([totalForce, dots]);
maxForce = Math.max(maxForce, Math.abs(totalForce));
}
}
}
}
console.log(calculatedFields);
// draw the lines from the arrays of dots here...
}
var charges = [
{charge: 6, x: 50, y: 75},
{charge: -5, x: 60, y: 254.5}
]
drawEqLines(charges);
You have a loop with code that says: dots.push(curPt)
In that loop, you reassign the x and y properties of the curPt object, but it's the same object that you keep pushing on each iteration.
You will have to create a new Point object inside the loop if you want to push different points into the array.

Force calculation for magnetic pendulum and numerical integration

I've been working on a simulation of a magnetic pendulum (Magnetic Pendulum for reference). Now, I have a question concerning how you calculate the forces/acceleration:
In examples you find online of the magnetic pendulum (such as the one provided above), and other physics force and acceleration calculations, the forces are calculated at a starting position, the position updated according to time-step dt and then new forces at time t+dt calculated to get a new position and so on. Basic numerical integration, makes sense.
However, I noticed, that if I calculate the forces this way, things don't go as one would expect. For example: when the pendulum is attracted by a magnet it just stops at the particluar magnet even tough you would expect it to "overswing" a bit. Therefore, I introduced three variables for each force which is all previous forces added together, and now it somehow seems to work correctly.
I'm wondering if
the way of calculating the forces I used makes sense in a physics simulation and
if not, then what am I doing wrong? Because it seems to work for other people.
Here's my code:
p5.disableFriendlyErrors = true;
let magnete = [];
let particles = [];
var maganzahl = 3; //number of magnets
var magradius = 100; //radius of magnets from mid-point
var G = 0.002; //coefficient of force towards middle (gravity)
var R = 0.2; //friction coefficient
var h = 50; //height of bob over magnets
var M = 150000; //strength of magnets
var m = 1; //mass (might not work)
var dt = 0.25; //timestep
var d = 2; //pixel density
var counter2 = 0;
var Reset;
var end = false;
//--------------------------------------------
function setup() {
createCanvas(600, 600);
pixelDensity(d);
background(60);
Reset = createButton('Reset');
Reset.position(width + 19, 49);
Reset.mousePressed(resetcanvas);
//construction of magnets
for (var i = 0; i < maganzahl; i++) {
magnete.push(new Magnet((width / 2) + magradius * cos(TWO_PI * (i / maganzahl)), (height / 2) + magradius * sin(TWO_PI * (i / maganzahl)), i));
}
}
//construction of a new "starting position" by mouse-click
function mousePressed() {
if (mouseX < width && mouseY < height) {
particles.push(new Particle(mouseX, mouseY));
}
}
function draw() {
for (var i = 0; i < particles.length; i++) {
if (particles[i].counter < 1000) {
//5 updates per frame(to speed it up)
for (var k = 0; k < 5; k++) {
for (var j = 0; j < magnete.length; j++) {
particles[i].attracted(magnete[j]);
}
particles[i].update();
particles[i].show2();
}
} else if (particles[i].counter < 1001) {
particles[i].counter += 1;
var nearest = [];
for (var j = 0; j < magnete.length; j++) {
nearest.push(particles[i].near(magnete[j]));
}
if (nearest.indexOf(min(nearest)) == 0) {
var c = color("green");
}
if (nearest.indexOf(min(nearest)) == 1) {
var c = color("purple");
}
if (nearest.indexOf(min(nearest)) == 2) {
var c = color("orange");
}
if (nearest.indexOf(min(nearest)) == 3) {
var c = color("blue");
}
if (nearest.indexOf(min(nearest)) == 4) {
var c = color("red");
}
if (nearest.indexOf(min(nearest)) == 5) {
var c = color("yellow");
}
//show particle trace according to nearest magnet
particles[i].show(c);
}
}
//displaying magnets
for (var i = 0; i < magnete.length; i++) {
magnete[i].show();
}
//displaying mid-point
stroke(255);
circle(width / 2, height / 2, 3);
}
function resetcanvas() {
background(60);
}
function Particle(x, y) {
this.orgpos = createVector(x, y);
this.pos = createVector(x, y);
this.prev = createVector(x, y);
this.vel = createVector();
this.acc = createVector();
this.accpre = createVector();
this.accprepre = createVector();
this.velprediction = this.vel;
this.magnetf = createVector();
this.gravity = createVector();
this.friction = createVector();
this.shape = new Array();
this.counter = 0;
//calculating new positions
this.update = function() {
//predictor for velocity -> Beeman's algorithm
this.velprediction.add(this.accpre.mult(3 / 2 * dt).add(this.accprepre.mult(-1 / 2 * dt)));
var momgrav = createVector(width / 2 - this.pos.x, height / 2 - this.pos.y);
var momfric = createVector(this.velprediction.x, this.velprediction.y);
momgrav.mult(G * m); //force due to gravity
momfric.mult(-R); //force due to friction
this.gravity.add(momgrav);
this.friction.add(momfric);
//a = F/m
this.acc = createVector((this.magnetf.x + this.gravity.x + this.friction.x) / m, (this.magnetf.y + this.gravity.y + this.friction.y) / m);
//-=Beeman's Algorithm=-
this.vel.add(this.acc.mult(dt * 1 / 3).add(this.accpre.mult(dt * 5 / 6)).add(this.accprepre.mult(-1 / 6 * dt)));
this.pos.add(this.vel.mult(dt).add(this.accpre.mult(dt * dt * 2 / 3)).add(this.accprepre.mult(-1 / 6 * dt * dt)));
this.accprepre = createVector(this.accpre.x, this.accpre.y);
this.accpre = createVector(this.acc.x, this.acc.y);
this.velprediction = createVector(this.vel.x, this.vel.y);
this.counter += 1;
this.shape.push(new p5.Vector(this.pos.x, this.pos.y));
}
//calculating force due to magnets -> attracted called earlier than update in sketch.js
this.attracted = function(target) {
var magn = createVector(target.pos.x - this.pos.x, target.pos.y - this.pos.y);
var dist = sqrt(sq(h) + sq(magn.x) + sq(magn.y)); //distance bob - magnet
strength = M / (Math.pow(dist, 3));
magn.mult(strength);
this.magnetf.add(magn);
}
//calculating distance to target
this.near = function(target) {
var dist = sqrt(sq(h) + sq(this.pos.x - target.pos.x) + sq(this.pos.y - target.pos.y));
return (dist);
}
//trace
this.show = function(col) {
beginShape();
stroke(col);
for (var i = 0; i < this.shape.length - 1; i++) {
line(this.shape[i].x, this.shape[i].y, this.shape[i + 1].x, this.shape[i + 1].y);
strokeWeight(2);
noFill();
}
endShape();
}
//dots
this.show2 = function() {
strokeWeight(1)
point(this.pos.x, this.pos.y);
}
}
function Magnet(x, y, n) {
this.pos = createVector(x, y);
this.n = n;
this.show = function() {
noStroke();
//color for each magnet
if (n == 0) {
fill("green");
}
if (n == 1) {
fill("purple");
}
if (n == 2) {
fill("orange");
}
if (n == 3) {
fill("blue");
}
if (n == 4) {
fill("red");
}
if (n == 5) {
fill("yellow");
}
strokeWeight(4);
circle(this.pos.x, this.pos.y, 10);
}
}
Any help would be greatly appreciated!
I found the issue! So apparently in p5.js you have to be careful with your vector calculations. If you for example do something like:
[some variable] = [Vector].add([anotherVector].mult(2));
both [Vector] and [anotherVector] change their value. Makes sense now that I think about it...
The fact that it still seemed to work somewhat "realistically" and that I managed to generate some beautiful pictures using it (Such as this one 1 and this one 2) is still quite mysterious to me but I guess sometimes numbers just do their magic ;)
Run it:
Code Preview
If you want to change some variables/edit:
p5.js Web Editor

Javascript - interactive particle logo not working

I'm working through instructions to construct an interactive particle logo design and can't seem to get to the finished product. This is the logo image file -
I'm using a canvas structure / background. Here's the code -
var canvasInteractive = document.getElementById('canvas-interactive');
var canvasReference = document.getElementById('canvas-reference');
var contextInteractive = canvasInteractive.getContext('2d');
var contextReference = canvasReference.getContext('2d');
var image = document.getElementById('img');
var width = canvasInteractive.width = canvasReference.width = window.innerWidth;
var height = canvasInteractive.height = canvasReference.height = window.innerHeight;
var logoDimensions = {
x: 500,
y: 500
};
var center = {
x: width / 2,
y: height / 2
};
var logoLocation = {
x: center.x - logoDimensions.x / 2,
y: center.y - logoDimensions.y / 2
};
var mouse = {
radius: Math.pow(100, 2),
x: 0,
y: 0
};
var particleArr = [];
var particleAttributes = {
friction: 0.95,
ease: 0.19,
spacing: 6,
size: 4,
color: "#ffffff"
};
function Particle(x, y) {
this.x = this.originX = x;
this.y = this.originY = y;
this.rx = 0;
this.ry = 0;
this.vx = 0;
this.vy = 0;
this.force = 0;
this.angle = 0;
this.distance = 0;
}
Particle.prototype.update = function() {
this.rx = mouse.x - this.x;
this.ry = mouse.y - this.y;
this.distance = this.rx * this.rx + this.ry * this.ry;
this.force = -mouse.radius / this.distance;
if (this.distance < mouse.radius) {
this.angle = Math.atan2(this.ry, this.rx);
this.vx += this.force * Math.cos(this.angle);
this.vy += this.force * Math.sin(this.angle);
}
this.x += (this.vx *= particleAttributes.friction) + (this.originX - this.x) * particleAttributes.ease;
this.y += (this.vy *= particleAttributes.friction) + (this.originY - this.y) * particleAttributes.ease;
};
function init() {
contextReference.drawImage(image, logoLocation.x, logoLocation.y);
var pixels = contextReference.getImageData(0, 0, width, height).data;
var index;
for (var y = 0; y < height; y += particleAttributes.spacing) {
for (var x = 0; x < width; x += particleAttributes.spacing) {
index = (y * width + x) * 4;
if (pixels[++index] > 0) {
particleArr.push(new Particle(x, y));
}
}
}
};
init();
function update() {
for (var i = 0; i < particleArr.length; i++) {
var p = particleArr[i];
p.update();
}
};
function render() {
contextInteractive.clearRect(0, 0, width, height);
for (var i = 0; i < particleArr.length; i++) {
var p = particleArr[i];
contextInteractive.fillStyle = particleAttributes.color;
contextInteractive.fillRect(p.x, p.y, particleAttributes.size, particleAttributes.size);
}
};
function animate() {
update();
render();
requestAnimationFrame(animate);
}
animate();
document.body.addEventListener("mousemove", function(event) {
mouse.x = event.clientX;
mouse.y = event.clientY;
});
document.body.addEventListener("touchstart", function(event) {
mouse.x = event.changedTouches[0].clientX;
mouse.y = event.changedTouches[0].clientY;
}, false);
document.body.addEventListener("touchmove", function(event) {
event.preventDefault();
mouse.x = event.targetTouches[0].clientX;
mouse.y = event.targetTouches[0].clientY;
}, false);
document.body.addEventListener("touchend", function(event) {
event.preventDefault();
mouse.x = 0;
mouse.y = 0;
}, false);
html,
body {
margin: 0px;
position: relative;
background-color: #000;
}
canvas {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
img {
display: none;
width: 70%;
height: 400px;
position: absolute;
left: 50%;
transform: translate(-50%, 30%);
}
<html>
<body>
<canvas id="canvas-interactive"></canvas>
<canvas id="canvas-reference"></canvas>
<img src="https://i.stack.imgur.com/duv9h.png" alt="..." id="img">
</body>
</html>
My understanding is the image file has to be set to display: none; and then the image needs to be re-drawn using the javascript commands but I'm not sure if this image is compatible or not. When finished I want the image on a white background.
By way of an example the end design needs to resemble this - Logo particle design
Particle positions from bitmap.
To get the FX you want you need to create a particle system. This is just an array of objects, each with a position, the position where they want to be (Home), a vector defining their current movement, and the colour.
You get each particle's home position and colour by reading pixels from the image. You can access pixel data by rendering an image on a canvas and the using ctx.getImageData to get the pixel data (Note image must be on same domain or have CORS headers to access pixel data). As you read each pixel in turn, if not transparent, create a particle for that pixel and set it colour and home position from the pixels colour and position.
Use requestAnimationFrame to call a render function that every frame iterates all the particles moving them by some set of rules that give you the motion you are after. Once you have move each particle, render them to the canvas using simple shapes eg fillRect
Mouse interaction
To have interaction with the mouse you will need to use mouse move events to keep track of the mouse position relative to the canvas you are rendering to. As you update each particle you also check how far it is from the mouse. You can then push or pull the particle from or to the mouse (depending on the effect you want.
Rendering speed will limit the particle count.
The only issue with these types of FX is that you will be pushing the rendering speed limits as the particle count goes up. What may work well on one machine, will run very slow on another.
To avoid being too slow, and not looking good on some machines you should consider keeping an eye on the frame rate and reducing the particle count if it runs slow. To compensate you can increase the particle size or even reduce the canvas resolution.
The bottleneck is the actual rendering of each particle. When you get to large numbers the path methods really grinds down. If you want really high numbers you will have to render pixels directly to the bitmap, using the same method as reading but in reverse of course.
Example simple particles read from bitmap.
The example below uses text rendered to a canvas to create the particles, and to use an image you would just draw the image rather than the text. The example is a bit overkill as I ripped it from an old answer of mine. It is just as an example of the various ways to get stuff done.
const ctx = canvas.getContext("2d");
const Vec = (x, y) => ({x, y});
const setStyle = (ctx,style) => { Object.keys(style).forEach(key => ctx[key] = style[key]) }
const createImage = (w,h) => {var i=document.createElement("canvas");i.width=w;i.height=h;i.ctx=i.getContext("2d");return i}
const textList = ["Particles"];
var textPos = 0;
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
var globalTime;
var started = false;
requestAnimationFrame(update);
const mouse = {x : 0, y : 0, button : false}
function mouseEvents(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
["down","up","move"].forEach(name => document.addEventListener("mouse"+name,mouseEvents));
function onResize(){
cw = (w = canvas.width = innerWidth) / 2;
ch = (h = canvas.height = innerHeight) / 2;
if (!started) { startIt() }
}
function update(timer){
globalTime = timer;
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.globalAlpha = 1; // reset alpha
if (w !== innerWidth || h !== innerHeight){ onResize() }
else { ctx.clearRect(0,0,w,h) }
particles.update();
particles.draw();
requestAnimationFrame(update);
}
function createParticles(text){
createTextMap(
text, 60, "Arial",
{ fillStyle : "#FF0", strokeStyle : "#F00", lineWidth : 2, lineJoin : "round", },
{ top : 0, left : 0, width : canvas.width, height : canvas.height }
)
}
// This function starts the animations
function startIt(){
started = true;
const next = ()=>{
var text = textList[(textPos++ ) % textList.length];
createParticles(text);
setTimeout(moveOut,text.length * 100 + 12000);
}
const moveOut = ()=>{
particles.moveOut();
setTimeout(next,2000);
}
setTimeout(next,0);
}
// the following function create the particles from text using a canvas
// the canvas used is displayed on the main canvas top left fro reference.
var tCan = createImage(100, 100); // canvas used to draw text
function createTextMap(text,size,font,style,fit){
const hex = (v)=> (v < 16 ? "0" : "") + v.toString(16);
tCan.ctx.font = size + "px " + font;
var width = Math.ceil(tCan.ctx.measureText(text).width + size);
tCan.width = width;
tCan.height = Math.ceil(size *1.2);
var c = tCan.ctx;
c.font = size + "px " + font;
c.textAlign = "center";
c.textBaseline = "middle";
setStyle(c,style);
if (style.strokeStyle) { c.strokeText(text, width / 2, tCan.height / 2) }
if (style.fillStyle) { c.fillText(text, width / 2, tCan.height/ 2) }
particles.empty();
var data = c.getImageData(0,0,width,tCan.height).data;
var x,y,ind,rgb,a;
for(y = 0; y < tCan.height; y += 1){
for(x = 0; x < width; x += 1){
ind = (y * width + x) << 2; // << 2 is equiv to * 4
if(data[ind + 3] > 128){ // is alpha above half
rgb = `#${hex(data[ind ++])}${hex(data[ind ++])}${hex(data[ind ++])}`;
particles.add(Vec(x, y), Vec(x, y), rgb);
}
}
}
particles.sortByCol
var scale = Math.min(fit.width / width, fit.height / tCan.height);
particles.each(p=>{
p.home.x = ((fit.left + fit.width) / 2) + (p.home.x - (width / 2)) * scale;
p.home.y = ((fit.top + fit.height) / 2) + (p.home.y - (tCan.height / 2)) * scale;
})
.findCenter() // get center used to move particles on and off of screen
.moveOffscreen() // moves particles off the screen
.moveIn(); // set the particles to move into view.
}
// basic particle
const particle = { pos : null, delta : null, home : null, col : "black", }
// array of particles
const particles = {
items : [], // actual array of particles
mouseFX : { power : 12,dist :110, curve : 2, on : true },
fx : { speed : 0.3, drag : 0.6, size : 4, jiggle : 1 },
// direction 1 move in -1 move out
direction : 1,
moveOut () {this.direction = -1; return this},
moveIn () {this.direction = 1; return this},
length : 0,
each(callback){ // custom iteration
for(var i = 0; i < this.length; i++){ callback(this.items[i],i) }
return this;
},
empty() { this.length = 0; return this },
deRef(){ this.items.length = 0; this.length = 0 },
sortByCol() { this.items.sort((a,b) => a.col === b.col ? 0 : a.col < b.col ? 1 : -1 ) },
add(pos, home, col){ // adds a particle
var p;
if(this.length < this.items.length){
p = this.items[this.length++];
p.home.x = home.x;
p.home.y = home.y;
p.delta.x = 0;
p.delta.y = 0;
p.col = col;
}else{
this.items.push( Object.assign({}, particle,{ pos, home, col, delta : Vec(0,0) } ) );
this.length = this.items.length
}
return this;
},
draw(){ // draws all
var p, size, sizeh;
sizeh = (size = this.fx.size) / 2;
for(var i = 0; i < this.length; i++){
p = this.items[i];
ctx.fillStyle = p.col;
ctx.fillRect(p.pos.x - sizeh, p.pos.y - sizeh, size, size);
}
},
update(){ // update all particles
var p,x,y,d;
const mP = this.mouseFX.power;
const mD = this.mouseFX.dist;
const mC = this.mouseFX.curve;
const fxJ = this.fx.jiggle;
const fxD = this.fx.drag;
const fxS = this.fx.speed;
for(var i = 0; i < this.length; i++){
p = this.items[i];
p.delta.x += (p.home.x - p.pos.x ) * fxS + (Math.random() - 0.5) * fxJ;
p.delta.y += (p.home.y - p.pos.y ) * fxS + (Math.random() - 0.5) * fxJ;
p.delta.x *= fxD;
p.delta.y *= fxD;
p.pos.x += p.delta.x * this.direction;
p.pos.y += p.delta.y * this.direction;
if(this.mouseFX.on){
x = p.pos.x - mouse.x;
y = p.pos.y - mouse.y;
d = Math.sqrt(x * x + y * y);
if(d < mD){
x /= d;
y /= d;
d /= mD;
d = (1-Math.pow(d, mC)) * mP;
p.pos.x += x * d;
p.pos.y += y * d;
}
}
}
return this;
},
findCenter(){ // find the center of particles maybe could do without
var x,y;
y = x = 0;
this.each(p => { x += p.home.x; y += p.home.y });
this.center = Vec(x / this.length, y / this.length);
return this;
},
moveOffscreen(){ // move start pos offscreen
var dist,x,y;
dist = Math.sqrt(this.center.x * this.center.x + this.center.y * this.center.y);
this.each(p => {
var d;
x = p.home.x - this.center.x;
y = p.home.y - this.center.y;
d = Math.max(0.0001,Math.sqrt(x * x + y * y)); // max to make sure no zeros
p.pos.x = p.home.x + (x / d) * dist;
p.pos.y = p.home.y + (y / d) * dist;
});
return this;
},
}
canvas { position : absolute; top : 0px; left : 0px; background : black;}
<canvas id="canvas"></canvas>
Use png saved as PNG-8 and and allow cross-origin
I saw the cool article from Bricks and mortar and thought I'd try it out.
I battled with it for an eternity, thinking that my js was wrong... Turns out that the image has to be saved as a PNG-8 without dither instead of a PNG-24.
Then make sure that you add the crossOrigin="Anonymous" attribute to the image tag:
<img crossOrigin="Anonymous" id="img" src="[link to wherever you host the image]" alt="logo">
I also hid the reference canvas by adding the following styles:
canvas#canvas-reference {
display: none;
}
I also added a debounce and resize function, so it's responsive.
The result:
See Demo with inverted logo

Where should I place this condition?

For the last step of this project, I want the growing circle to stop when it collides with another circle. The isOnCircle function already checks for this successfully when creating a new circle. However, when adding the condition !isOnCircle to my grow() function (line 61) it prevents any new circles from being added.
function grow() {
var a = circles[circles.length - 1];
if (!isOnCircle(a)){
a.radius += 1;
}}
Perhaps the circle is being created first, then in the check for collision, it's colliding with itself. Where else could I put the !isOnCircle check so that it gets checked at every radius increase and stops the grow function then?
check this
//set up canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var circles = [];
//create circle
function create(location) {
circles.push({
x: location.x,
y: location.y,
radius: 10,
color: '#' + Math.floor(Math.random() * 16777215).toString(16)
});
}
//figure out mouse position
var rect = document.getElementById("canvas").getBoundingClientRect();
// Get canvas offset on page
var offset = {
x: rect.left,
y: rect.top
};
function isOnCanvas(a) {
if ((a.x >= 0 && a.x <= rect.width) && (a.y >= 0 && a.y <= rect.height)) {
return true;
}
return false;
}
function isOnCircle(a) {
var i = 0,
l = circles.length,
x, y, d, c;
for (; i < l; ++i) {
c = circles[i];
x = a.x - c.x;
y = a.y - c.y;
d = (a.radius || 10) + c.radius;
if (x * x + y * y <= d * d) {
return true;
}
}
return false;
}
// draw all circles
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < circles.length; i++) {
var p = circles[i];
ctx.beginPath();
ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI);
ctx.fillStyle = p.color;
ctx.fill();
}
}
//make last drawn circle 1px bigger
function grow() {
var a = circles[circles.length - 1];
a.radius += 1;
}
//find percentage of canvas filled in
var totalSpace = canvas.width * canvas.height;
var totalFilled = function () {
total = 0;
for (var i = 0; i < circles.length; i++) {
var p = circles[i];
total += Math.PI * Math.pow(p.radius, 2);
}
return total;
console.log(total);
}
function findPercentage() {
return (totalFilled() / totalSpace) * 100;
}
function updateInfo() {
percentage = findPercentage();
document.getElementById("percentage").innerHTML = "You've filled in " + percentage.toFixed(1) + "%";
}
//do all the stuff
var animate = function () {
grow();
draw();
updateInfo();
}
//put this outside function so we can stop it later
var growLoop;
window.onmousedown = function (e) {
// get event location on page offset by canvas location
var location = {
x: e.pageX - offset.x,
y: e.pageY - offset.y
};
if (isOnCanvas(location) && !isOnCircle(location)) {
create(location);
draw();
updateInfo();
growLoop = setInterval(animate, 100);
}
};
window.onmouseup = function () {
clearInterval(growLoop);
}
window.onmouseout = function () {
clearInterval(growLoop);
}
it's colliding with itself.
Probably. You definitely should avoid that in the collision detection:
function isOnCircle(a) {
var l = circles.length,
x, y, d, c;
for (var i = 0; i < l; ++i) {
c = circles[i];
if (a == c) // add these
continue; // two lines!
x = a.x - c.x;
y = a.y - c.y;
d = (a.radius || 10) + c.radius;
if (x * x + y * y <= d * d) {
return true;
}
}
return false;
}
It is colliding with itself. Since you know the current circle will always be the last one in circles you can modify isOnCircle like this:
l = circles.length - 1,
so that it won't check against the current circle.
http://jsfiddle.net/SeAGU/91/

Ball Bounce - javascript

function randomXToY(minVal,maxVal,floatVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}
Ball = (function() {
// constructor
function Ball(x,y,radius,color){
this.center = {x:x, y:y};
this.radius = radius;
this.color = color;
this.dx = 2;
this.dy = 2;
this.boundaryHeight = $('#ground').height();
this.boundaryWidth = $('#ground').width();
this.dom = $('<p class="circle"></p>').appendTo('#ground');
// the rectange div a circle
this.dom.width(radius*2);
this.dom.height(radius*2);
this.dom.css({'border-radius':radius,background:color});
this.placeAtCenter(x,y);
}
// Place the ball at center x, y
Ball.prototype.placeAtCenter = function(x,y){
this.dom.css({top: Math.round(y- this.radius), left: Math.round(x - this.radius)});
this.center.x = Math.round(x);
this.center.y = Math.round(y);
};
Ball.prototype.setColor = function(color) {
if(color) {
this.dom.css('background',color);
} else {
this.dom.css('background',this.color);
}
};
// move and bounce the ball
Ball.prototype.move = function(){
var diameter = this.radius * 2;
var radius = this.radius;
if (this.center.x - radius < 0 || this.center.x + radius > this.boundaryWidth ) {
this.dx = -this.dx;
}
if (this.center.y - radius < 0 || this.center.y + radius > this.boundaryHeight ) {
this.dy = -this.dy;
}
this.placeAtCenter(this.center.x + this.dx ,this.center.y +this.dy);
};
return Ball;
})();
var number_of_balls = 5;
var balls = [];
$('document').ready(function(){
for (i = 0; i < number_of_balls; i++) {
var boundaryHeight = $('#ground').height();
var boundaryWidth = $('#ground').width();
var y = randomXToY(30,boundaryHeight - 50);
var x = randomXToY(30,boundaryWidth - 50);
var radius = randomXToY(15,30);
balls.push(new Ball(x,y,radius, '#'+Math.floor(Math.random()*16777215).toString(16)));
}
loop();
});
loop = function(){
for (var i = 0; i < balls.length; i++){
balls[i].move();
}
setTimeout(loop, 8);
};
I have never used in oops concepts in javascript. How do I change the ball color when the balls touches each other?
This is the link : http://jsbin.com/imofat/1/edit
You currently don't have any interaction with the balls. What you can do is checking whether two balls are "inside" each other, and change colors in that case: http://jsbin.com/imofat/1491/.
// calculates distance between two balls
var d = function(a, b) {
var dx = b.center.x - a.center.x;
var dy = b.center.y - a.center.y;
return Math.sqrt(dx*dx + dy*dy);
};
and:
// for each ball
for(var i = 0; i < balls.length; i++) {
// check against rest of balls
for(var j = i + 1; j < balls.length; j++) {
var a = balls[i];
var b = balls[j];
// distance is smaller than their radii, so they are inside each other
if(d(a, b) < a.radius + b.radius) {
// set to some other color using your random color code
a.setColor('#'+Math.floor(Math.random()*16777215).toString(16));
b.setColor('#'+Math.floor(Math.random()*16777215).toString(16));
}
}
}
Still, there are things for improvement:
Balls are changing colors as long as they are inside each other, not just once.
If you want them to "touch", you might want to implement some kind of bouncing effect to make it more realistic.

Categories