drawing within an if statement of a function in P5.JS - javascript

I want to basically make it that when the record button is pressed and the recording is taking place, that the audio that is being recorded is visualized as per the code in the draw function and then once that is done, the user would be able to save/playback the recording. I think I need to move the content of the draw function somewhere within the if statements of the canvasPressed function but I have no idea how. I'd appreciate any guidance. I am experimenting and adding different bits from different sources so my entire code might be jumbled up and wrong to begin with though the recording, playback, saving part of the code works fine on its own, it's just the drawing bit that doesn't. Thank you in advance.
let mic;
let volHistory = [];
var angle = 0;
let recorder, soundFile;
let state = 0;
function setup() {
let cnv = createCanvas(100, 100);
cnv.mousePressed(canvasPressed);
background(220);
textAlign(CENTER, CENTER);
// create an audio in
mic = new p5.AudioIn();
// prompts user to enable their browser mic
mic.start();
// create a sound recorder
recorder = new p5.SoundRecorder();
// connect the mic to the recorder
recorder.setInput(mic);
// this sound file will be used to
// playback & save the recording
soundFile = new p5.SoundFile();
text('tap to record', width/2, height/2);
}function canvasPressed() {
// ensure audio is enabled
userStartAudio();
// make sure user enabled the mic
if (state === 0 && mic.enabled) {
// record to our p5.SoundFile
recorder.record(soundFile);
background(255,0,0);
text('Recording!', width/2, height/2);
state++;
}
else if (state === 1) {
background(0,255,0);
// stop recorder and
// send result to soundFile
recorder.stop();
text('Done! Tap to play and download', width/2, height/2, width - 20);
state++;
}
else if (state === 2) {
soundFile.play(); // play the result!
save(soundFile, 'mySound.wav');
state++;
}
}
function draw() {
background(51);
let vol = mic.getLevel();
volHistory.push(vol);
translate(width/2, height/2)
noFill();
beginShape();
for (let i = 0; i < 360; i++) {
stroke(255);
let r = map(volHistory[i], 0, 1, 10, 300);
let x = r * cos(i);
let y = r * sin(i);
vertex(x, y);
}
endShape();
if(volHistory.length > 360) {
volHistory.splice(0,1);
}
// ellipse(300, 300, vol*300, vol*300);
// console.log(vol)
}
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>

Related

Object Detection and Recognition in JS

I wanted to develop object detection system using ml5 & p5.js,where I can upload an image and system can provide me an output image with Rectangle around objects in image. Yolo and Cocossd datasets are working fine for recognition an object in image.
Like this image object is being identified:
But these datasets are not giving me results for detection where there is text or object with text. As I am expecting system to identify each word of text as different object, like for below image :
Result should be like this:
Rectangle around K
Rectangle around F
Rectangle around C
and one Rectangle around logo of KFC
Please help regarding this or suggest any other system which i can use in PHP/Js to detect objects in image.
let img;
let detector;
function preload(){
img = loadImage('e.jpeg');
detector = ml5.objectDetector('yolo');
}
function setup() {
createCanvas(800, 800);
image(img,0,0);
detector.detect(img,gotDetections);
}
function gotDetections(error, result){
if(error){
console.log(error)
}
console.log(result)
drawResults(result);
// for (let i = 0 ; i< result.length; i++){
// let object = result[i];
// stroke(0,255,255);
// strokeWeight(4);
// noFill();
// rect(object.x ,object.y,object.width,object.height);
// }
}
function drawResults(results) {
results.forEach((result) => {
// Generates a random color for each object
const r = Math.random()*256|0;
const g = Math.random()*256|0;
const b = Math.random()*256|0;
// Draw the text
stroke(0, 0, 0);
strokeWeight(2);
textSize(16);
fill(r, g, b);
text(`${result.label} (${result.confidence.toFixed(2)}%)`, result.x, result.y - 10);
// Draw the rectangle stroke
noFill();
strokeWeight(3);
stroke(r, g, b);
rect(result.x, result.y, result.width, result.height);
});
};
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<script src="https://unpkg.com/ml5#latest/dist/ml5.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<main>
</main>
<script src="sketch.js"></script>
</body>
</html>

How to shift an array of posenet points?

I'm a beginner at using p5.js but I'm currently currently attempting to create a brush sketch like this
ellipse brush
though using computer vision & posenet nose tracking (essentially a nose brush)
The problem is, while it doesn't state any errors, it doesn't work.
This is my code for the ellipse brush without posenet & camera vision
let mousePosition = [];
function setup() {
createCanvas(400, 400);
}
function draw() {
background(0);
//Every frame of animation
//storing the mouse position in an array
mousePosition.push({x: mouseX, y: mouseY});
//shift the array so that the older ones deletes itself
if(mousePosition.length > 100) mousePosition.shift();
//loop
for(let i = 0; i < mousePosition.length; i++) {
//if the variable is less than 50, loop function
let x = mousePosition[i].x;
let y = mousePosition[i].y;
ellipse(x, y, r,r);
var r = 20
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
and this is the one with computer vision & nose tracking w/ posenet
let capture;
let poseNet;
let pose;
let text;
let pg;
let nosePosition = []
function setup() {
createCanvas(700, 700);
capture = createCapture(VIDEO);
capture.hide();
pg = createGraphics(width, height);
poseNet = ml5.poseNet(capture, modelLoaded);
poseNet.on('pose', gotPoses);
// background(255)
// color picker
}
function gotPoses(poses) {
//console.log(poses);
if (poses.length > 0) {
pose = poses[0].pose;
}
}
function modelLoaded() {
console.log('poseNet.ready');
}
function draw() {
translate(width, 0); // move to far corner
scale(-1.0, 1.0); // flip x-axis backwards
image(capture, 0, 0, width, width * capture.height /
capture.width);
image(pg, 0, 0, width, height);
if (pose) {
nosePosition.push({x:pose.nose.x ,y: pose.nose.y});
if(nosePosition.length > 100) nosePosition.shift(); {
}
for(let i = 0; i < nosePosition.length; i++) {
//if the variable is less than 50, loop function
let x = nosePosition[i].x;
let y = nosePosition[i].y;
pg.ellipse(x, y, i/5,i/5);
var r = 20 //how big the ellipse is
pg.fill(255)
pg.noStroke();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/addons/p5.sound.min.js"></script>
<script src="https://unpkg.com/ml5#latest/dist/ml5.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
The second is essentially very similar to the first, as I've only changed the mouseX/Ys into the posenet Nose keypoint.
Any insight/solution would be highly appreciated!
Thank you :)
You're shifting properly, but you forgot to clear the pg graphic, which is kind of like forgetting to put background(0) in your original sketch. So instead of drawing all the ellipses on a blank background, you're drawing them on top of the previous frame.
Adding pg.clear() anywhere in draw() after you display pg on the canvas (image(pg, ...)) and before you draw the ellipses (for (...) {... ellipse(nosePosition[i].x...)}) should do the trick. Here's where I put it:
image(pg, 0, 0, width, height);
pg.clear();//HERE
if (pose) {//...

Game froze in <canvas> js

I`m writing a pong game on js and html using canvas. Besides main body of the game I have the starting menu with "play button"(all the buttons are just images i counted their coordinates and just use ), then next menu where user chooses the background and then eventually game itself and then after reaching 3 points by user or computer the game ends and there's a win or fail window appering where you can press the "back to menu" button and go back to the very first menu with "play button" and start everything again. Program does everything okay when you first launch it but after you for example lose and go back to main menu, choose the background, game starts aaaaaaand when ball reaches 2 points the game get frozen and sometimes after minute or so somehow loads the menu with backgrounds. I really have no idea what's wrong and why it gets frozen and strangely on the second time you play. Please help me ;((
PS. Im just a beginner idk how to insert the images here in stackoverflow
const canvas = document.getElementById("pongping");
const context = canvas.getContext('2d');
/////////////1)function to draw the rect
function drawPryamokutnik(x,y,w,h,color) {
context.fillStyle = color;
context.fillRect(x,y,w,h);
}
//////////////////////2)рисуем круг ///////////////////////////////////////////////////////////////////////////////
function drawKolo(x,y,radius,color) {
context.fillStyle = color;
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2, false);
context.closePath();
context.fill();
}
///////////////////////3)drawText/////////////////////////////////////////////
function drawText(text,x,y,color){
context.fillStyle = color;
context.font = "80px Arial";
context.fillText(text,x,y);
}
///////////////////////4)создаем пластинку пльзователя//////////////////////////////////////////////////////////////
const rectleft = {
x:20,
y:canvas.height/2-100,
width: 25,
height: 200,
color: "WHITE",
score:0
};
///////////////////////5)создаем пластинку компьютера//////////////////////////////////////////////////////////////
const rectright = {
x:canvas.width-45,
y:canvas.height/2-100,
width: 25,
height: 200,
color: "WHITE",
score:0
};
///////////////////////6)создаем шайбу/////////////////////////////////////////////////////////////////////////////
const ball = {
x: canvas.width/2,
y: canvas.height/2,
speed: 5,
radius: 20,
velocityX: 5,
velocityY: 5,
colour:"WHITE"
};
//////////////////////8)создаем разделительную сетку///////////////////////////////////////////////////////////////
const net = {
x:canvas.width/2-1,
y:0,
width: 2,
height:10,
color:"WHITE"
};
//////////////////////9)создаем функцию сетки/////////////////////////////////////////////////////////////////////
function drawNet(){
for(let i=0; i<=canvas.height;i+=15)
{
drawPryamokutnik(net.x,net.y+i,net.width,net.height,net.color)
}
}
//drawPryamokutnik(0,0,canvas.width, canvas.height, "BLACK");
//drawText("so you wanna die young?",200,300,"WHITE");
canvas.addEventListener("mousemove",moovePaddle);
function moovePaddle(etv){
let rect=canvas.getBoundingClientRect();
rectleft.y=etv.clientY-rect.top-rectleft.height/2;
}
function update(){
ball.x += ball.velocityX;
ball.y += ball.velocityY;
let computerLevel= 0.1;
rectright.y+=(ball.y-(rectright.y+rectright.height/2))*computerLevel;
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.velocityY = -1 * ball.velocityY;
}
let player = (ball.x>canvas.width/2)? rectright:rectleft;
if(colission(ball,player)){
let collidePoint = ball.y - (player.y + player.height / 2);
collidePoint = collidePoint /(player.height / 2);
let angleRead = Math.PI/4 * collidePoint;
let direction = (ball.x < canvas.width / 2) ? 1 : -1;
ball.velocityX = direction * ball.speed * Math.cos(angleRead);
ball.velocityY = direction * ball.speed * Math.sin(angleRead);
ball.speed += 1;
}
if (ball.x - ball.radius < 0 ){
rectright.score++;
ResetBall();
}
else if(ball.x+ball.radius>canvas.width)
{rectleft.score++;
ResetBall();}
}
function ResetBall() {
ball.x=canvas.width/2;
ball.y=canvas.height/2;
ball.speed=5;
ball.velocityX=-ball.velocityX;
}
function colission(b,p){
b.top=b.y-b.radius;
b.bottom=b.y+b.radius;
b.left=b.x-b.radius;
b.right=b.x+b.radius;
p.top=p.y;
p.bottom=p.y+p.height;
p.left=p.x;
p.right=p.x+p.width;
return b.right>p.left && b.bottom>p.top && b.left<p.right && b.top < p.bottom;
}
function render(){
const back = new Image();
if(backchek===1)
{back.src = "back1.png";}
if(backchek===2)
{back.src = "back2.png";}
if(backchek===3)
{back.src = "back3.png";}
context.drawImage(back, 0, 0);
//drawPryamokutnik(0,0,canvas.width,canvas.height,"BLACK");
drawNet();
drawText(rectleft.score,canvas.width/4,canvas.height/5,"WHITE");
drawText(rectright.score,3*canvas.width/4,canvas.height/5,"WHITE");
drawPryamokutnik(rectleft.x,rectleft.y,rectleft.width,rectleft.height,rectleft.color);
drawPryamokutnik(rectright.x,rectright.y,rectright.width,rectright.height,rectright.color);
drawKolo(ball.x,ball.y,ball.radius,ball.colour);
}
let slide;
function game() {
slide=1;
menu();
if(startcheck===true)
{backchoose();
slide=2;
if(backchek===1||backchek===2||backchek===3)
{render();
update();
if(rectright.score>2)
{
losing();
slide=3;
// startcheck=false;
if(backagain===true)
{slide=1;
game();
}}
if(rectleft.score>2)
{//startcheck=false;
winning();
slide=3;
if(backagain===true)
{slide=1;
game();
}}
}
}
}
let framePerSecond=65;
setInterval(game,1000/framePerSecond);
function menu(){
const menuu = new Image();
menuu.src = "menu.png";
context.drawImage(menuu, 0, 0);
}
function losing(){
const lose = new Image();
lose.src = "lose.png";
context.drawImage(lose, 0, 0);
}
function winning(){
const win = new Image();
win.src = "win.png";
context.drawImage(win, 0, 0);
}
function backchoose(){
const backk = new Image();
backk.src = "back choose .png";
context.drawImage(backk, 0, 0);
}
let backchek;
let backagain=false;
let startcheck=false;
canvas.addEventListener("mousedown", clicked, false);
function clicked(e){
e.preventDefault();
let rectt=canvas.getBoundingClientRect();
const x = e.clientX;
const y = e.clientY - rectt.top;
let xprtr;
let yprtr;
let hipot;
let yby;
let xby;
let yey;
let xex;
if(x===496 && y===471&& slide===1)
{startcheck=true;
//backagain=false;
}
if(x>496){xprtr=x-496;}
if(x<496){xprtr=496-x;}
if(y>471){yprtr=y-471;}
if(y<471){yprtr=471-y;}
hipot=yprtr*yprtr+xprtr*xprtr;
if(hipot<=10609&&slide===1)
{startcheck=true;}
if(slide===2&&(y>217&&y<430&&x>75&&x<404)){backchek=1;}
if(slide===2&&(y>217&&y<430&&x>585&&x<924)){backchek=2;}
if(slide===2&&(y>508&&y<773&&x>344&&x<675)){backchek=3;}
if(slide===3&&y>519&&(y<702&&x>224&&x<768))
{backagain=true;
backchek=0;
startcheck=false;
rectright.score=0;
rectleft.score=0;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pong20</title>
</head>
<body>
<canvas id="pongping" width="1000" height="800"></canvas>
<script src="pongping.js"></script>
</body>
Does anything pop up in the console? That might give some hint as to what is going wrong.
I noticed that in your game() function you are recursively calling game(). This may cause a recursive overflow.
At the same time, you have setInterval calling game again and again. I recommend you delete the lines:
let framePerSecond=65;
setInterval(game,1000/framePerSecond);
and replace them with
window.requestAnimationFrame(game)
This will still initialize your game properly, but it will also not block the thread, so users can still interact with the page as expected. It may not keep the proper frame rate that you're expecting, but that function passes a timestamp to the function it calls, so you could keep track of the time since last call and update movements based on that. Check out this example.
then inside your game function, replace every call to
game()
with
window.requestAnimationFrame(game)
This will hopefully stop your game from crashing.
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

Make identical objects move independently in Javascript Canvas

So I am trying to make a simple space game. You will have a ship that moves left and right, and Asteroids will be generated above the top of the canvas at random X position and size and they will move down towards the ship.
How can I create Asteroid objects in seperate positions? Like having more than one existing in the canvas at once, without creating them as totally seperate objects with seperate variables?
This sets the variables I would like the asteroid to be created on.
var asteroids = {
size: Math.floor((Math.random() * 40) + 15),
startY: 100,
startX: Math.floor((Math.random() * canvas.width-200) + 200),
speed: 1
}
This is what I used to draw the asteroid. (It makes a hexagon shape with random size at a random x coordinate)
function drawasteroid() {
this.x = asteroids.startX;
this.y = 100;
this.size = asteroids.size;
ctx.fillStyle = "#FFFFFF";
ctx.beginPath();
ctx.moveTo(this.x,this.y-this.size*0.5);
ctx.lineTo(this.x+this.size*0.9,this.y);
ctx.lineTo(this.x+this.size*0.9,this.y+this.size*1);
ctx.lineTo(this.x,this.y+this.size*1.5);
ctx.lineTo(this.x-this.size*0.9,this.y+this.size*1);
ctx.lineTo(this.x-this.size*0.9,this.y);
ctx.fill();
}
I included ALL of my code in this snippet. Upon running it, you will see that I currently have a ship that moves and the asteroid is drawn at a random size and random x coordinate. I just need to know about how to go about making the asteroid move down while creating other new asteroids that will also move down.
Thank You for all your help! I am new to javascript.
// JavaScript Document
////// Variables //////
var canvas = {width:300, height:500, fps:30};
var score = 0;
var player = {
x:canvas.width/2,
y:canvas.height-100,
defaultSpeed: 5,
speed: 10
};
var asteroids = {
size: Math.floor((Math.random() * 40) + 15),
startY: 100,
startX: Math.floor((Math.random() * canvas.width-200) + 200),
speed: 1
}
var left = false;
var right = false;
////// Arrow keys //////
function onkeydown(e) {
if(e.keyCode === 37) {
left = true;
}
if(e.keyCode === 39) {
right = true;
}
}
function onkeyup(e) {
if (e.keyCode === 37) {
left = false;
}
if(e.keyCode === 39) {
right = false;
}
}
////// other functions //////
//function to clear canvas
function clearCanvas() {
ctx.clearRect(0,0,canvas.width,canvas.height);
}
// draw the score in the upper left corner
function drawscore(score) {
var score = 0;
ctx.fillStyle = "#FFFFFF";
ctx.fillText(score,50,50);
}
// Draw Player ship.
function ship(x,y) {
var x = player.x;
var y = player.y;
ctx.fillStyle = "#FFFFFF";
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x+15,y+50);
ctx.lineTo(x-15,y+50);
ctx.fill();
}
// move player ship.
function moveShip() {
document.onkeydown = onkeydown;
document.onkeyup = onkeyup;
if (left === true && player.x > 50) {
player.x -= player.speed;
}
if (right === true && player.x < canvas.width - 50) {
player.x += player.speed;
}
}
// Draw Asteroid
function drawasteroid() {
this.x = asteroids.startX;
this.y = 100;
this.size = asteroids.size;
ctx.fillStyle = "#FFFFFF";
ctx.beginPath();
ctx.moveTo(this.x,this.y-this.size*0.5);
ctx.lineTo(this.x+this.size*0.9,this.y);
ctx.lineTo(this.x+this.size*0.9,this.y+this.size*1);
ctx.lineTo(this.x,this.y+this.size*1.5);
ctx.lineTo(this.x-this.size*0.9,this.y+this.size*1);
ctx.lineTo(this.x-this.size*0.9,this.y);
ctx.fill();
}
// move Asteroid
function moveAsteroid() {
//don't know how I should go about this.
}
// update
setInterval (update, 1000/canvas.fps);
function update() {
// test collisions and key inputs
moveShip();
// redraw the next frame of the animation
clearCanvas();
drawasteroid();
drawscore();
ship();
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Game</title>
<script src="game-functions.js"></script>
<!--
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
-->
</head>
<body>
<canvas id="ctx" width="300" height="500" style="border: thin solid black; background-color: black;"></canvas>
<br>
<script>
////// Canvas setup //////
var ctx = document.getElementById("ctx").getContext("2d");
</script>
</body>
</html>
You want to make the creation of asteroids dynamic...so why not set up a setInterval that gets called at random intervals as below. You don't need a separate declaration for each Asteroids object you create. You can just declare a temporary one in a setInterval function. This will instantiate multiple different objects with the same declaration. Of course you need to store each object somewhere which is precisely what the array is for.
You also have to make sure that asteroids get removed from the array whenever the moveAsteroid function is called if they are off of the canvas. The setInterval function below should be called on window load and exists alongside your main rendering setInterval function.
You are also going to have to change your moveAsteroid function a bit to be able to point to a specific Asteroids object from the array. You can do this by adding the Asteroids object as a parameter of the function or by making the function a property of the Asteroids class and using this. I did the latter in the example below.
var astArray = [];
var manageAsteroidFrequency = 2000;
var Asteroids {
X: //something
Y://something
speed:1
move: function() {
this.X -= speed;
}
}
var mainRenderingFunction = setInterval( function() {
for (var i = astArray.length-1 ; i > -1; i --){
if(astArray[i].Y < 0){
astArray.splice(i, 1)
}else{
astArray[i].move;
}
}
}, 40);
var manageAsteroids = setInterval( function () {
if (astArray.length < 4){
var tmpAst = new Asteroids();
astArray.push(tmpAst);
}
manageAsteroidFrequency = Math.floor(Math.random()*10000);
}, manageAsteroidFrequency);

How do you get p5.js into a website?

I have searched nearly all over the internet, and i've gotten pretty close to an answer, but I still can't figure out how to use p5.js in a website. To be more specific, i want to be able to perhaps create a weebly, and have it display p5 code. i know it involves the website loading the p5.js through a file or the online file, and the sketch.js. If there is no way to use p5.js on the web, is there any way to use processing code in general(or something similar) on the internet? Thanks
Follow these instructions: http://p5js.org/get-started/
Or these instructions: https://github.com/processing/p5.js/wiki/Embedding-p5.js
In other words, you need to create an html file that uses p5.js, which you should already have.
Then you need to upload that html file, along with any resources you're using, to some kind of web host.
You might also want to check out Processing.js, which comes with the standard Processing editor.
creat html file and a sketch.js file
in your html file you can put in a starter template and then add p5js in the sketch.js
check the docs here
// All the paths
var paths = [];
// Are we painting?
var painting = false;
// How long until the next circle
var next = 0;
// Where are we now and where were we?
var current;
var previous;
function setup() {
createCanvas(720, 400);
current = createVector(0,0);
previous = createVector(0,0);
};
function draw() {
background(200);
// If it's time for a new point
if (millis() > next && painting) {
// Grab mouse position
current.x = mouseX;
current.y = mouseY;
// New particle's force is based on mouse movement
var force = p5.Vector.sub(current, previous);
force.mult(0.05);
// Add new particle
paths[paths.length - 1].add(current, force);
// Schedule next circle
next = millis() + random(100);
// Store mouse values
previous.x = current.x;
previous.y = current.y;
}
// Draw all paths
for( var i = 0; i < paths.length; i++) {
paths[i].update();
paths[i].display();
}
}
// Start it up
function mousePressed() {
next = 0;
painting = true;
previous.x = mouseX;
previous.y = mouseY;
paths.push(new Path());
}
// Stop
function mouseReleased() {
painting = false;
}
// A Path is a list of particles
function Path() {
this.particles = [];
this.hue = random(100);
}
Path.prototype.add = function(position, force) {
// Add a new particle with a position, force, and hue
this.particles.push(new Particle(position, force, this.hue));
}
// Display plath
Path.prototype.update = function() {
for (var i = 0; i < this.particles.length; i++) {
this.particles[i].update();
}
}
// Display plath
Path.prototype.display = function() {
// Loop through backwards
for (var i = this.particles.length - 1; i >= 0; i--) {
// If we shold remove it
if (this.particles[i].lifespan <= 0) {
this.particles.splice(i, 1);
// Otherwise, display it
} else {
this.particles[i].display(this.particles[i+1]);
}
}
}
// Particles along the path
function Particle(position, force, hue) {
this.position = createVector(position.x, position.y);
this.velocity = createVector(force.x, force.y);
this.drag = 0.95;
this.lifespan = 255;
}
Particle.prototype.update = function() {
// Move it
this.position.add(this.velocity);
// Slow it down
this.velocity.mult(this.drag);
// Fade it out
this.lifespan--;
}
// Draw particle and connect it with a line
// Draw a line to another
Particle.prototype.display = function(other) {
stroke(0, this.lifespan);
fill(0, this.lifespan/2);
ellipse(this.position.x,this.position.y, 8, 8);
// If we need to draw a line
if (other) {
line(this.position.x, this.position.y, other.position.x, other.position.y);
}
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html>
If you are creating your sketch using the editor for Mac or Windows (Version 0.5.7 (0.5.7) as of this writing), go to "Save As" and the editor will export your "web ready" files.
Your saved file will have the same name as your sketch and will include an index.html and sketch.js file along with a "libraries" folder. You can post the .html and .js files as-is and inspect the .html for links to the p5 .js libraries.
<script src="libraries/p5.js" type="text/javascript"></script>
<script src="libraries/p5.dom.js" type="text/javascript"></script>
<script src="libraries/p5.sound.js" type="text/javascript"></script>
<script src="sketch.js" type="text/javascript"></script>

Categories