Trouble with converting a sketch from processing to p5js

I have trouble with converting one of my sketches to p5.js. If i run this in the web browser, the canvas doesn't show up anyway.

Any suggestions?

Thanks a lot!

function setup() {
  createCanvas(600, 400);
    colorMode(HSB, 100, 100, 100);
  background(bg);
  strokeCap(SQUARE);

// Variablen

var a = 0;
var b = 10;
var c = 100;
var d = 0;
var bg = 10;
var fg = 90;

var activeSketch = 0;
var sketchCount = 2;
var g = random(5, 11);
var mystroke = 1;
var trianglex = random(10, 800);
var triangley = random(10, 800);
var triangleWidth = 50;

var nullkomma = 0.0;



}

function draw() {
background(0);


  // Steuerung durch die Tastatur: Q, W, E, R, T, Z


  if (keyPressed) {

    if (key == 'q' || key == 'Q') {
      q();
    }
    if (key == 'w' || key == 'W') {
      w();
    }  
    if (key == 'e' || key == 'E') {
      e();
    }  
    if (key == 'r' || key == 'R') {
      r();
    }
    if (key == 't' || key == 'T') {
      t();
    }
    if (key == 'z' || key == 'Z') {
      z();
    }

  } else {
    a = 0;
    b = 10;
    nullkomma = 0;
    noStroke();
    fill(10, 100);
    rect(0, 0, width, height);
  }
  a++;
    println(a);


    colorMode(HSB, 100, 100, 100);
    strokeWeight(1);

}

function w()
{
  background(bg);
    stroke(fg);
    strokeWeight(a);
  line(a*a, 0, a*a, height);
  line(width-a*a, 0, width-a*a, height);
}

function e()
{
  background(fg);
  noStroke();
  fill(bg);
  for (var i = 0; i < a*50; i++) {
    ellipse(random(width), random(height), 3+a/2, 3);
  }
}


function r()
{
  noStroke();
  fill(bg, 40);
  rect(0, 0, width, height);
  fill(fg);
  noStroke();
  for (var j = 0; j < a; j++) {
    ellipse(random(width), random(height), 20, 20);
  }
}

function t()
{
  noStroke();
  fill(bg, 90);
  rect(0, 0, width, height);
  fill(fg);
  noStroke();
  for (var j = 0; j < 1+a*100; j++) {
    ellipse(random(width), random(height), 4, 4);
  }
}

function z()
{
  noStroke();
  fill(bg, 50);
  rect(0, 0, width, height);
  for (var j = 0; j < 10; j++) {
    fill(fg);
    rect(random(width), 0, random(2, 10), height);
  }
}

Answers

  • edited November 2015 Answer ✓
    • For starters, keyword void doesn't exist in JS! b-(
    • You've got lotsa redundancy in your big code.
    • Many lines could be easily replaced by loops w/ the right increment.
    • For keyboard input, keyPressed() callback is the better option.
    • Also notice keyPressed is called keyIsPressed in p5.js.
    • JS doesn't distinguish variables from functions btW. So watch out if they use same name! :-S
    • Notice that each key invokes a function of the same name.
    • You can reduce everything to 1 statement only if you use method(str(char(keyCode))); in Java.
    • For JS, eval() would do the same: eval(String.fromCharCode(keyCode) + '();');
    • In short, shorten your original "Java Mode" sketch before attempting to convert it to p5.js. B-)
  • edited November 2015 Answer ✓

    On first sight:

    • declare your variables on top, outside of setup()
    • random() will not work there, so you would have to initiate some of the values in setup()
    • replace void with function
    • replace float with var
    • change keyPressed to keyIsPressed

    There might be more probems, but i didn' test your code.

  • Hi guys!! Man thanks! I'm going to work it out!

  • edited November 2015

    BtW, I've got some sketches for both Java/JS Mode & p5.js:
    https://forum.Processing.org/two/discussion/8997/hoppy-beaver
    https://forum.Processing.org/two/discussion/7147/some-simple-pulse-equations-using-trig

    So you can have a better idea how a Processing sketch can be converted to p5.js. :D

    P.S.: Processing to p5.js tutorial:
    https://GitHub.com/processing/p5.js/wiki/Processing-transition

  • edited November 2015

    You can reduce everything to 1 statement only if you use method(str(char(keyCode))); in Java. For JS, eval() would do the same: eval(String.fromCharCode(keyCode) + '();');

    @GoToLoop: :-S :-& 8-X

    Generally speaking eval is something to avoid in JS (this article has a good explanation); though it does occasionally have its uses. This definitely isn't one of them. Unlike in Java, it's very easy to call a function from a string input. You can reference it from the global context - in a browser this will be window - like so:

    window["functionName"]();

    But I wouldn't recommend that. Again unlike in Java, it's very quick and easy to create convenience objects:

    var bgColour = [0, 0, 0];
    
    function setup() {
        createCanvas(600, 400);   
    }
    
    function draw() {
        background(bgColour);
    }
    
    // handle keyPressed in associated event handler
    function keyPressed() {
        // one simple approach to getting key value
        console.info(key);
        var keyAction = keyActions[key.toLowerCase()];
    
        // IMPORTANT: check there's a function set for this character
        // Note: you could go a step further and make sure
        // it's actually of type function too...
        if(keyAction) {
            keyAction();
        }
    }
    
    
    // Wrap our key events up in an object
    // avoids pollution of global scope.  Particularly important
    // when using fairly anonymous function names like this!
    var keyActions = {
    
        "a" : function() {
            bgColour = [255,0,0];
        },
        "b" : function() {
            bgColour = [0,255,0];
        },
        "c" : function() {
            bgColour = [0,0,255];
        }
    
    }
    

    Edit: I just made a minor change to my code. I noticed the warning on the p5js documentation for 'key': "Not Guaranteed to be Case Sensitive"...

  • edited November 2015

    Generally speaking eval() is something to avoid in JS...
    This definitely isn't one of them.

    • @injuvik has asked for suggestions about converting his original "Java Mode" sketch to P5.JS.
    • I've suggested him to 1st clean up his original Java code before trying the conversion.
    • 1 of my advises was to place the whole keyboard logic inside keyPressed().
    • And additionally, compact all of those function calls as 1 method("") statement.
    • The corresponding approach for it in JS is eval("").
    • @blindfish, I wasn't trying to teach him exclusive JS techniques w/o clear corresponding Java 1s.
    • But rather showing where Java & JS share syntaxes, so he can convert sketches between those.
  • edited November 2015

    In order to demo what I've meant by keyPressed() + method()/eval(), I've worked on 2 versions for the same sketch: Java Mode & P5.JS.

    You can also check out P5.JS flavor in online action below:
    http://p5js.ProcessingTogether.com/sp/pad/export/ro.Ca0XtGgd$dJc59


    "Java Mode"


    /**
     * Method Eval Sample (v1.0)
     * Java/p5.js Cross-Mode
     * GoToLoop (2015-Nov-01)
     * 
     * forum.Processing.org/two/discussion/13345/
     * trouble-with-converting-a-sketch-from-processing-to-p5js
     *
     * p5js.ProcessingTogether.com/sp/pad/export/ro.Ca0XtGgd$dJc59
     */
    
    static final color BG = 0350, FG = 0200;
    static final short STROKE = 0100, BOLDNESS = 10;
    
    void setup() {
      size(600, 400);
      smooth(4);
      noLoop();
      background(0);
    
      fill(FG);
      stroke(STROKE);
      strokeCap(SQUARE);
      strokeWeight(BOLDNESS);
    
      rectMode(CORNER);
      ellipseMode(CENTER);
    }
    
    void draw() {
    }
    
    void keyPressed() {
      final int  k = keyCode;
      final char letter = char(k + 040);
      println(key, k, letter);
    
      if (letter >= 'a' & 'c' >= letter) {
        background(BG);
        method(str(letter));
        redraw();
      }
    }
    
    void a() {
      line(0, 0, width, height);
      line(width, 0, 0, height);
    }
    
    void b() {
      rect(0, 0, width>>1, height>>1);
    }
    
    void c() {
      ellipse(width>>1, height>>1, width>>1, height>>1);
    }
    


    "P5.JS Mode"


    /**
     * Method Eval Sample (v1.0)
     * Java/p5.js Cross-Mode
     * GoToLoop (2015-Nov-01)
     * 
     * forum.Processing.org/two/discussion/13345/
     * trouble-with-converting-a-sketch-from-processing-to-p5js
     *
     * p5js.ProcessingTogether.com/sp/pad/export/ro.Ca0XtGgd$dJc59
     */
    
    const BG = 0350, FG = 0200, STROKE = 0100, BOLDNESS = 10;
    
    function setup() {
      createCanvas(600, 400);
      fill(FG).stroke(STROKE).strokeCap(SQUARE).strokeWeight(BOLDNESS);
      rectMode(CORNER).ellipseMode(CENTER).background(0).noLoop();
    }
    
    function draw() {
    }
    
    function keyPressed() {
      const k = keyCode, letter = String.fromCharCode(k + 040);
      console.info(key, k, letter);
    
      if (letter >= 'a' & 'c' >= letter) {
        background(BG);
        eval(letter + '();');
        redraw();
      }
    }
    
    function a() {
      line(0, 0, width, height).line(width, 0, 0, height);
    }
    
    function b() {
      rect(0, 0, width>>1, height>>1);
    }
    
    function c() {
      ellipse(width>>1, height>>1, width>>1, height>>1);
    }
    

  • edited November 2015

    I noticed the warning on the p5js documentation for 'key': "Not Guaranteed to be Case Sensitive"...

    Actually they've screwed key for keyPressed() callback for next 0.4.18 release version! X(

    That serious regression and deviation from Processing happened here:
    https://GitHub.com/processing/p5.js/pull/1013

    The actual "fix" attempt here:
    https://GitHub.com/processing/p5.js/pull/1013/files#diff-ccc04c6b9ccad70d45ab5e13aa0c8aa9R172

    if (e.key >= 'a' && e.key <= 'z') {
      tempKeyCode = e.keyCode + 32;
    }
    
    this._setProperty('keyCode', tempKeyCode);
    

    Basically rather than actually fix key so it can distinguish between lower & upper case characters, they've just decided to alter keyCode to be all lower case too! 8-}
    In short, keyCode = key inside keyPressed() for next version!!!

    By Processing's convention, keyCode can't hold lowercase characters ever! ~X(

    I'm baffled that @shiffman himself, who was always involved w/ Processing, requested "that": :-&
    https://GitHub.com/processing/p5.js/issues/536

  • @GoToLoop: you were the one who suggested using method() in Java :P

    You can reduce everything to 1 statement only if you use method(str(char(keyCode))); in Java. For JS, eval() would do the same: eval(String.fromCharCode(keyCode) + '();');


    I wasn't trying to teach him exclusive JS techniques w/o clear corresponding Java 1s. But rather showing where Java & JS share syntaxes, so he can convert sketches between those.

    I think this is an issue that will keep re-occurring as people try to convert between Processing and p5js. Just because there are apparent 'equivalents' doesn't mean you should use them.

    It's a similar problem to spoken language translation. If you take a dictionary and do word for word translation to a language you don't know fluently you may manage to create something that is understood; but it won't be as fluid/natural as if you first developed a proper understanding of the target language.

Sign In or Register to comment.