EzDevInfo.com

p5.js

p5.js is a JS client-side library for creating graphic and interactive experiences, based on the core principles of Processing. <a href="http://twitter.com/p5xjs">http://twitter.com/p5xjs</a> — p5.js p5.js a js client-side library for creating graphic and interactive experiences, based on the core principles of processing.

Why does this object property return NaN?

I have a undefined object at the top of my page:

var paddelY = {};

Then IN the draw loop, I define it (Otherwise I get an error that mouseY is undefined):

paddelY = { 
    1 : mouseY + height*0.03,  //Nuber
    2 : this[1] - height*0.00275 //NaN
};

However, if I were to log paddelY[2] to the console, it would be NaN.


Source: (StackOverflow)

p5.js onclick redraw the rectangle

I would like to redraw the rectangle inside the circle when it is clicked; can anyone suggest an idea?

function setup() {
createCanvas(700, 500);
  // Starts in the middle
  x = width / 2;
  y = height / 2;
}

function draw() {
    background(10);
    stroke(1000);
    fill(10);
    ellipse(x, y, 300, 300);

    rect(80, 80, 100, 50);
    rect(550, 180, 100, 50);
    rect(150, 400, 100, 50);
}

function mousePressed() {
    //question
}

remove() wipes out the entire canvas.


Source: (StackOverflow)

Advertisements

Is there anyway that I can give a div a function in p5.js

Im trying to take a div that I created and make it move across the screen every hour using p5.js and I'm wondering if that is at all possible I was also wonderig if that div can change color randomly every hour in p5.js


Source: (StackOverflow)

creating a particle system using animated gifs as the particle

I am trying to create a particle system using an animated gif image as the particle. What I initially tried was using Dan Shiffman's particle system code in p5.js, and replacing the particles with animated gif images. However it seems that p5.js does not support animated gifs as images.

My question is what other way can I accomplish this? What library or tool will allow me to create a particle system of animated gifs, that will interact with the mouse, in my HTML page?


Source: (StackOverflow)

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


Source: (StackOverflow)

Using gradient orientations to direct brush stroke effect in Javascript

I'm trying to recreate in Javascript (specifically with p5.js) an effect others seem to have successfully accomplished using the Mathematica suite, as seen here http://mathematica.stackexchange.com/a/39049.

I'm 100% ignorant about Mathematica, but I see they are using a method called GradientOrientationFilter to create a pattern of strokes following the direction of the gradients of the image.

oil brushes

My results are still not satisfying.

The logic I'm using

  • create a histogram of oriented gradients, evaluating the luma values, then finding the horizontal and vertical gradient, and it's direction and magnitude;
  • draw a line at each pixel to represent the gradient direction with a random grayscale color. I will use these lines later, blended with the actual picture.

The code:

var img, vectors;

var pixelsToSkip = 2; // for faster rendering we can stroke less lines
var linesLength = 20;
var strokeThickness = 1; 

function preload() { 
  img = loadImage('http://lorempixel.com/300/400/people/1');
  img2 = loadImage('http://lorempixel.com/300/400/people/1');

  /* you can test in local if the directions are correct using a simple gradient as image
  img = loadImage('http://fornace.io/jstests/img/gradient.jpg');
  img2 = loadImage('http://fornace.io/jstests/img/gradient.jpg');
  */
}

function setup() {  
  createCanvas(img.width, img.height);
  noLoop();
  img.loadPixels();


  makeLumas();
  makeGradients();
  makeVectors();

  for ( var xx = 0; xx < img.width; xx = xx + pixelsToSkip) {
    for ( var yy = 0; yy < img.height; yy = yy + pixelsToSkip) {
      push();
        stroke(random(255));  // to color with pixel color change to stroke(img.get(xx, yy));
        strokeWeight(strokeThickness);
        translate(xx,yy);
        rotate( vectors[yy][xx].dir ); // here we use the rotation of the gradient
        line(-linesLength/2, 0, linesLength/2, 0);
      pop();
    }
  }

//      adding the image in overlay to evaluate if the map is good
//      tint(255, 255, 255, 100);
//      image(img2,0,0);


}

function draw() {
}




function makeLumas() {
// calculate the luma for each pixel to get a map of dark/light areas ("Rec. 601") https://en.wikipedia.org/wiki/Luma_(video)
  lumas = new Array(img.height);
  for (var y = 0; y < img.height; y++) {
    lumas[y] = new Array(img.width);

    for (var x = 0; x < img.height; x++) {
      var i = x * 4 + y * 4 * img.width;
      var r = img.pixels[i],
          g = img.pixels[i + 1],
          b = img.pixels[i + 2],
          a = img.pixels[i + 3];

      var luma = a == 0 ? 1 : (r * 299/1000 + g * 587/1000
        + b * 114/1000) / 255;

      lumas[y][x] = luma;
    }
  }
}

function makeGradients() {
// calculate the gradients (kernel [-1, 0, 1])

  var horizontalGradient = verticalGradient = [];

  for (var y = 0; y < img.height; y++) {
    horizontalGradient[y] = new Array(img.width);
    verticalGradient[y] = new Array(img.width);

    var row = lumas[y];

    for (var x = 0; x < img.width; x++) {
      var prevX = x == 0 ? 0 : lumas[y][x - 1];
      var nextX = x == img.width - 1 ? 0 : lumas[y][x + 1];
      var prevY = y == 0 ? 0 : lumas[y - 1][x];
      var nextY = y == img.height - 1 ? 0 : lumas[y + 1][x];

      horizontalGradient[y][x] = -prevX + nextX;
      verticalGradient[y][x] = -prevY + nextY;
    }
  }
}

function makeVectors() {
// calculate direction and magnitude

  vectors = new Array(img.height);

  for (var y = 0; y < img.height; y++) {
    vectors[y] = new Array(img.width);

    for (var x = 0; x < img.width; x++) {
      var prevX = x == 0 ? 0 : lumas[y][x - 1];
      var nextX = x == img.width - 1 ? 0 : lumas[y][x + 1];
      var prevY = y == 0 ? 0 : lumas[y - 1][x];
      var nextY = y == img.height - 1 ? 0 : lumas[y + 1][x];

      var gradientX = -prevX + nextX;
      var gradientY = -prevY + nextY;

      vectors[y][x] = {
        mag: Math.sqrt(Math.pow(gradientX, 2) + Math.pow(gradientY, 2)),
        dir: Math.atan2(gradientY, gradientX)
      }
    }
  }
}

The results on a image

My field made in javascript is much more noisy than the one made in Mathematica.

http://jsfiddle.net/frapporti/b4zxkcmL/

results

Final note

I'm quite new to p5.js, perhaps I'm reinventing the wheel in some passage. Feel free to correct me in this too.

Fiddle: http://jsfiddle.net/frapporti/b4zxkcmL/


Not very relevant to the question, but playing with the values some nice effect comes out. I thought I'd share. http://jsfiddle.net/frapporti/hL0Lexjj/ enter image description here


Source: (StackOverflow)

How to send data from a mysql database to JS scrip?

My intention is to query an MySQL database using a PHP script and then send the information to Java Script.

I know how to encode the info into the JSON and send the request to the server script.

How does the PHP script know it has been queried it should answer?


Source: (StackOverflow)

Why is this object not in scope?

See the code example below:

( function(){
  var test = new p5(
    function ( p ){
       var x = new Quad(); // Quad is undefined
    }
  ),

  Quad = function(){
     // some code
  }
})();

I suspect it has to do with the external library (p5 in this example) because the anonymous function is executed within the context of new p5(), but I don't understand it.

I thought that because Quad was defined within the main closure's scope, it should be available to anything defined within that closure...

Can you explain to me why my thinking is wrong?


Source: (StackOverflow)

Extracting info from a JSON: P5.js

my php script json_encodes this:

[{"x":"20","y":"24","name":"NewNov"},{"x":"20","y":"70","name":"Tito"}]

But I can't see how I can extract this information in my p5.js program?

Say, I need to use those 'x', 'y', 'name' to draw a circle in the appropriate place with the right name.

I used loadJSON in the script, and now I have a variable -

data = loadJSON()

But how do I get, say, the 'x' component from the JSON?

var radius;

function preload() {
    var url = 'http://localhost/planetTrequest.php';
    radius = loadJSON(url);
}

function setup() {
    createCanvas(300, 300);
    background(153);
    noLoop();
}

function draw() {
    background(200);
    textSize(15);
    text(radius.x, 10, 30);
    fill(0, 102, 153);
}

Source: (StackOverflow)

how can I remove the submit button after its clicked on p5 dom

I am brand new to javascript and I am attempting to create a type your adventure game. I am using DOM on p5.js. I would like the submit button to disappear after you type "your heroes name." Also, I would like the rest of the game to have a multiple choice answer type set up, so if you could also help find a starting point on that it would be very helpful. Thank you.

var input, button, greeting;
var a;

function setup() {


  // create canvas
  createCanvas(710, 400);



  input = createInput();
  input.position(20, 100);

  button = createButton('submit');
  button.position(200, 150);
  button.mousePressed(greet);

  greeting = createElement('h2', 'what is the name of your hero?');
  greeting.position(20, 5);


  textAlign(CENTER)
  textSize(50);
}

function greet() {
  var name = input.value();
  greeting.html(name+' lives in a peaceful and beautiful village called Scranton.  The only village not yet completely ravaged by the chaos and war surrounding daily life everywhere else.');
  input.value('');

     text(name, 0, 0);


}

Source: (StackOverflow)

p5.js how to translate along axes after rotate

After I rotated an coordinates system it is translating along its new axes. Is it somehow possible to translate it along axes before rotation?

Idea is that user uploads an image and then he can rotate it, zoom it and move it around the middle of the viewport. Somehow I failt o achive all of those functions ta once.

Any suggestions?

EDIT

I.e. there is a canvas. I draw an image there. Then I rotate it 90° and I want to translate it on X axis. It moves down the screen. Because axes are turned around.

EDIT

Here is a code snippet that I use for transformation. Image is rotated always in it's (0,0) point. That is why I translate it in a way that it is rotatet in its middle point. Afterwards I draw the image in an offset point.

    p.push();
        p.translate(canvasWidth/2, canvasHeight/2);
        p.rotate(angle * p.TWO_PI/360);

        var x = -loadedImage.width/2  - offsetX;
        var y = -loadedImage.height/2 - offsetY;

        p.image(loadedImage, x, y);
    p.pop();

EDIT

I decied to translate first, and then rotate. It makes translating correct but it rotates around wrong pivot point. I can't have everything I guess.


Source: (StackOverflow)

How do I send sound generated by Web Audio API from one website to another using socket.io and Node.js?

I am working on an application that involves sending the sound output from a series of webpages to a central page that plays all the outputs simultaneously. Right now, I'm using p5 (the Processing JavaScript library, which is basically just a wrapper on the WebAudio API), node.js, and socket.io.

I know it's possible to stream the microphone input to a server and then back to the client, but how would I do this with audio created in the browser with the WebAudio API? How do I turn the AudioContext output into binary data, stream it through the socket, and then play it back client-side? Any help would be greatly appreciated!


Source: (StackOverflow)

Creating a P5.js 2-Dimensional Array

I'm trying to port my working processing sketch to p5.js so I can use it online. But I'm running into a problem when trying to set the values in a 2 dimensional array. I think I'm following the correct syntax shown in the 2d array section of the API, but am getting an uncaught type error that says "cannot set property 0 of undefined".

The sketch is pretty simple, I'm just trying to read from a CSV and store the data in a 2D array:

var cols = 8;
var rows = 8;
var month = 1;
var values = [];
var table;

function preload(){
    table = loadTable("1988.csv", "csv");
}

function setup() {
    createCanvas(800, 800);
    var totalRows = table.getRowCount();

    for (var m = 0; m < 12; m++) {
        for (var c = 0; c < cols; c++) {
            values[c]=[];
            for (var r = 0; r < rows; r++) {
                values[r+m*rows][c] = table.getNum(m*rows*cols + c*rows + r, 0);
            }
        }
    }
}

Any help is very much appreciated!

Thank you for your time.


Source: (StackOverflow)

creating a simple processing p5.js library

I was trying to create a simple library and ran into problems. This is my html file:

`
<html>
    <script src = 'p5.min.js'></script>
    <script src = 'mosaic.js'></script>
    <script src = 'sketch.js'></script>
    <body>
        <script>setMosaic(true)</script>
    </body>
</html>
`

mosaic.js is the library I am creating.

The content of mosaic.js is :

`
p5.prototype._isMosaic = false;
p5.prototype.setMosaic = function(status){
    this._isMosaic = status;
    console.log('set worked');
  };
`

If I call setMosaic from inside the as shown in the html file, it gives me a function not defined error. But I can call setMosaic() successfully from inside setup() or draw() of sketch.js. Calling setMosaic from outside the sketch works when I define setMosaic in /src/environment/environment.js and build p5.js again.

Is there a way to call setMosaic from outside the sketch?

EDIT (in response to the comment):

1) I'm trying to build a framework that can scale the sketch into multiple screens. So the person who writes the sketch has to do it the normal way, but my tool will be calling some functions that communicates with a server e.t.c. So I need to call these functions outside the sketch, but they should be bound to the p5 object (namespace) because the functions I write in turn will have to call some functions internal to p5js. This is my project.

2) Value is going to be affected per sketch.


Source: (StackOverflow)

Function that filters what is shown using p5 and Javascript

new to javascript programming here. I'm using p5.js (and its p5.dom library) to create a bar chart visualization.

I have a dataset that lists people's names, heights, and the states they went to school in. Here is a partial snippet of it:

var height = [{name:"A",height:1,school:"FL"},
{name:"B",height:5,school:"MI"},
{name:"C",height:2,school:"MI"},
{name:"D",height:5,school:"CA"},
{name:"E",height:4,school:"FL"},
{name:"F",height:3,school:"MA"}]; 

I've also created a way to create a bar chart based on the height of each individual, as well as buttons for each school (to be explained further below):

function setup() {
  createCanvas(300,150);
  fill_color = color(125,125,125);

  h1 = createElement('h1', '');

  fl_button = createButton("FL", "FL");
  fl_button.mousePressed(filterschool);
  mi_button = createButton("MI", "MI");
  mi_button.mousePressed(filterschool);
  ca_button = createButton("CA", "CA");
  ca_button.mousePressed(filterschool);
  ma_button = createButton("MA", "MA");
  ma_button.mousePressed(filterschool);
  reset_button = createButton("reset", "reset");

}

function draw() {
  var idx = -1; 
  for (idx in height) {
    var heading = height[idx].name;
    var val = height[idx].height;

    //Bars
    fill(fill_color);
    stroke();
    rect(idx*15, 100, 10, -val*10);

    //Names
    fill(fill_color);
    noStroke();
    text(heading, idx*15+2, 115);
    }
}

Now, what I'd like to do is make it possible to filter what is seen based on the the school that each person attends. For example, if I click the "FL" button, I want to see only the bars pertaining to those students whose school value is "FL". I started writing a function to do this:

function filterschool(e) {
    alert(e.srcElement.value)
    if (value == "MI") {
        //create a new variable? not sure
    }
}

but I'm not sure how to properly set this up.

One attempt I made was to change function filterschool(e) to create a new variable:

function filterschool(e) {
    alert(e.srcElement.value)
    if (value == "MG") {
        school == value
    }
}

and then reference that new variable infunction draw():

if (height[idx].school == value) {
        fill(fill_color);
        stroke();
        rect(idx*15, 100, 10, -val*10);

    //Names
        fill(fill_color);
        noStroke();
        text(heading, idx*15+2, 115);
        }

but I wasn't sure how to define value in the function setup() to accept all school locations at the outset (before any button is pressed). Also, even if that worked, I'm not sure this whole approach would be correct anyway.

Any help would be greatly appreciated.


Source: (StackOverflow)