user3527705
user3527705

Reputation: 21

Processing js + javascript+ processing

I am trying to make a conection javascript-processing, using processing js, but it isn't working. The processing sketch appears on the website, but not the graphic with information.

javascript:

var base_url = "http://ws.audioscrobbler.com/2.0/";


var apikey = "***";

var base_request = "****";

var username;

var procura;
var getUserInfo;
var searching;
var log;

var proc;
var bound=false;

var listaArtistas = [];
var listaArtistasOther = [];




$(document).ready(function () {


    $("#pjs").hide();

    $("#go").click(function () {
        procura();


        //alert("go");

        $("#artists").click(function () {
            buscarArtistas("#search-text", false);
            buscarTracks();

            bindJavascript(listaArtistas);

            //alert("artists");
        });

        $("#compare").click(function () {
            buscarArtistas("#search-text", false);
            buscarArtistas("#search-user", true);
            //alert("compare");
        });
    });
});


function bindJavascript(listaArtistas){



       proc = Processing.getInstanceById('pjs');
       $("#pjs").show();


    if(proc!=null){

    proc.bindJavascript(this);
    proc.legenda(listaArtistas);
        bound=true;

    }else if(!bound){

        setTimout(bindJavascript,250);

    }

    bindJavascript();

}


function buscarArtistas(id, isOther) {
    username = $(id).val();
    searching();
    getUserTopArtists(username, isOther);
   // alert("buscarArtistas");
}

function buscarTracks() {
    username = $("#search-text").val();
    searching();
    getUserTracks();
    //alert("buscarTracks");

}



function procura() {
    username = $("#search-text").val();
    searching();
    getUserInfo();
    //alert("procura");
}

function getUserInfo() {
    var data = {
        api_key: apikey,
        method: "user.getInfo",
        user: username,
        format: "json"
    };
    $.ajax({
        url: base_url,
        data: data,
        success: processUserInfo
    });    
    //alert("getUserInfo");
}

function getUserTopArtists(user_, isOther) {
    var data_ = {
        api_key: apikey,
        method: "user.getTopArtists",
        user: user_,
        limit: 20,
        format: "json"        
    };    
    $.ajax({
        url: base_url,
        data: data_,
        async:   false,
        success: function (info) {
            processUserTopArtists(info, isOther);

            if (isOther) {
                comparar();
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

        }
    });    
    //alert("getUserTopArtists");
}



function processUserInfo(info) {    
    if (info.error) {        
        log("User " + username + " doesn´t  exist or the field is empty<br/>Try again...");       
        return;
    }    
    username = info.user.name;
    var realname = info.user.realname,
        pais = info.user.country,
        age = info.user.age,
        genero = info.user.gender,
        playlist = info.user.playlists;
    $("#profile").html("Username: " + username + " <br>Name:" + realname + " <br> Country:" + pais + " <br> Age:" + age + " <br> Gender:" + genero + "<br>Playlists:" + playlist + "<br/><table></table>");    
    //alert("processUserInfo");
}

function processUserTopArtists(info, isOther) {


    $.each(info.topartists.artist, function(index, artist) {
        if (isOther) {
            listaArtistasOther[index] = artist.name;


        } else {

         listaArtistas[index] = artist.name;


            $("#artistas").append("Artist: " + artist.name + "<br/>");

           //proc.funcao(listaArtistas[index]);

        }


    });

    //alert("processUserTopArtists");    
}

function comparar() {

    //alert ("lista art " + listaArtistas);
    //alert ("lista art Other " + listaArtistasOther);

    $.each(listaArtistas, function(index, item) {
        var index = $.inArray(item, listaArtistasOther);
        if (index >= 0) {
            $("#artistas2").append("Name: " + item + "<br/>");
        }
    });

    //alert("comparar");
}

function getUserTracks() {    
     var data_ = {
        api_key: apikey,
        method: "user.getTopTracks",
        user: username,
        limit: 100,
        format: "json"        
    }; 

    // alert ("getUserTracks");

$.ajax({
        url: base_url,
        data: data_,
        success: function (info) {
        processUserTopTracks(info);
        }

    });    

    //alert("Estou aqui");
}

function processUserTopTracks(info){    
   $.each(info.toptracks.track, function(index, track) {
        var track = track.name;        
        $("#tracks").append("Track: " + track + "<br/>");
    });
    //alert("aqui");
}

function searching() {    
    $("#status").empty();
    //alert("searching");
}
function log(message) {
    $("#status").append(message + "<br/>");    
    //alert("log");
}

processing file:

JavaScript js;

int planetsnum=4;
float ang=PI/4;
Stars [] star;
float [][] angsincs=new float [2][planetsnum];
color[] corplanetas=new color[planetsnum];


PFont font;
int totalStars=0;


 void legenda(String [] l){

    totalStars=0;

  String [] listaArtistas ={"",""};

     star= new Stars[totalStars];

   font = createFont("Courier New",12);


  for(int i=0; i<l.length; i++){



    listaArtistas[i]=l[i];

    star[i]= new Stars(new PVector(random(40,820),random(40,360)),20, planetsnum,listaArtistas[i],0);
totalStars++;



  }
   for(int w=0; w<planetsnum; w++){

     angsincs[0][w]=random(TWO_PI);
      angsincs[1][w]=random(0.00001, 0.0001);

      corplanetas[w]=color(random(50,255),random(50,255),random(50,255));
}


 }

void setup(){

size(900,400);


}

void draw(){

 background(0);


  for(int i=0; i<totalStars; i++){
    for(int j=0; j<totalStars; j++){

    if (j > i) {

    if(star[i].VerificaColisaoDeBolas(star[j])){
     star[j].localizacao.x=star[j].localizacao.x+ star[j].r;
      star[j].localizacao.y=star[j].localizacao.y+ star[j].r; 
}
}
}
}
 for(int i=0; i<totalStars; i++){
  star[i].displayStar();

   star[i].limites();

   for(int w=0; w<star[i].planetnum; w++){

   int raio=(w+1)*40;

     float a= star[i].localizacao.x+(raio/2)*cos(angsincs[0][w]);
    float b=star[i].localizacao.y+(raio/2)*sin(angsincs[0][w]);




    planetas(star[i].localizacao.x,star[i].localizacao.y,a,b,raio,corplanetas[w]); 


 angsincs[0][w]=angsincs[0][w]+angsincs[1][w];
    }
    }

    cimaEstrela();

 }


 void cimaEstrela(){

   PVector localizacaoRato = new PVector(mouseX, mouseY);


   for(int i =0; i<totalStars;i++){

    if(star[i].localizacao.dist(localizacaoRato)  <= star[i].r){

     star[i].d=255;


   }else{

     star[i].d=0;

   }
 }
 }


void planetas(float x,float y,float a1,float b1,int r2,color c){

  stroke(100);
      noFill();
      ellipse(x,y,r2,r2);

      fill(c);
      ellipse(a1,b1,10,10);
}

class Stars{   

  float r; 
  PVector localizacao;
  int planetnum;
  String s;
  int d;


 Stars(PVector tempXY, float tempR, int tempplanetnum, String temps, int tempd) {
    localizacao = tempXY;
   r=tempR;
   planetnum=tempplanetnum;
   d=tempd;
   s=temps;


  }

  void displayStar() {


  fill(255,d);
  text(s,localizacao.x+r, localizacao.y);


}

 boolean VerificaColisaoDeBolas(Stars outraStars) {
    float distanciaX = localizacao.dist((outraStars.localizacao));

    if (distanciaX < (r + outraStars.r)) {


      return true;
    }
    return false;
  }

  void limites() {

    if ((localizacao.x+(r)) > width) {
      localizacao.x = width - (r);

    }  
    else if ((localizacao.x-(r)) < 0) {
      localizacao.x = (r);

    }
    else if ((localizacao.y + (r)) > height) {
      localizacao.y = height - (r);

    }
    else if ((localizacao.y -(r)) < 0) {
      localizacao.y = r;

    }
  }

}

interface JavaScript {}

void bindJavascript(JavaScript script) {
js = script;
}

Any thoughts how to do this? Thanks in advance.

Upvotes: 0

Views: 503

Answers (1)

Winchestro
Winchestro

Reputation: 2188

Ok the problem is that you can not read local files (aka send XMLHttpRequests, short XHR) if you view your website locally from the file:// protocol. The reason is probably because otherwise it would be easy to trick people into opening websites locally and then have access to all their files I guess.

There are many ways you can solve this, the easiest would be to run a local server, like processing does for example when you test your processing.js sketch in javascript mode. Processing also allows you to define your own html/js/ccc to load instead of the default template. So maybe this would also be a quick solution.

You find it all the options you need by running Processing in JavaScript mode. Then you'll have a JavaScript menu where you can define the templates, and server settings.

Another way would be to upload it somewhere. (this approach has the advantage of allowing you to test it on different devices like your smartphone/tablet etc. or other people easily) On top of the many "traditional" free/paid web hosting services you could use to test it, notable alternatives are

  • Google Drive / Dropbox allow you to host your static content as websites
  • tumblr also hosts static content, but it's a bit more hassle to maintain than the first option
  • Github can also do the same thing but I've never tried it myself so far, so I can't tell you how exactly to set it up.
  • Heroku offers hosting for dynamic content free of charge for small scale projects, in case you want to do some server side scripting.

Another problem could also be if you request files from another domain, the XHR could also fail if the server doesn't support it, because it's per default blocked in browsers unless specifically allowed by the server. That's a problem if you have if you send these requests from client side script because this again is dangerous terrain where people apparently did quite a lot of hacking in the past.

It's a quite complicated topic and there is no way I can do it justice, but in case you want to read more about it "CORS" and "XHR" are good keywords to google.

Upvotes: 1

Related Questions