p5 js in react : Expected an assignment or function call and instead saw an expression no-unused-expressions

Viewed 219

When running this script on p5 js's sandbox it's working really fine When trying to use it inside react i get : Expected an assignment or function call and instead saw an expression no-unused-expressions

I checked previous questions and found out that most of the problems are syntax ones due to not using brackets or semicolons . I did all the good syntax practices but didn't get to make it function

Here is my sketch code on react :

export default function sketch(p){
      var t;
      var canvas ; 
      var w = window.innerWidth;
      var h = window.innerHeight;  
      var x , y , d , T;
      p.setup=()=>{

        // put setup code here
        t=0; 
        
      }
      p.draw = () => {
        canvas =p.createCanvas(w-50, h-50);
        canvas.style('display','block');
        
        var x_center = (p.windowWidth - w) / 2;
        var y_center = (p.windowHeight - h) / 2;
        canvas.position(x_center, y_center);
        
       t += .01;
        
        for (var j = 2; x = y = j--;){
          for (var i = w; d = p.noise(t - i / 99) * 3, i--; x += Math.cos(d) * 6, y += Math.sin(d) * 6){
               j ? i - w / 2 || ( T = p.translate)(-x, -y) : p.push() + T(x + w / 2, y + w / 2) + p.rotate(d + Math.PI / 4) + p.line(-600, 100, 600, 100) + p.pop(i % 100 || p.scale(80));
          
          }  
        }
      }

      window.onresize = function() {
        // assigns new values for width and height variables
        w = window.innerWidth;
        h = window.innerHeight;  
        canvas.size(w,h);
      }
}

1 Answers

Write out p.translate(x, y) every time rather than using T = p.translate and then T(x, y), e.g.,

export default function sketch(p){
    let t;
    let canvas ; 
    let w = window.innerWidth;
    let h = window.innerHeight;  
    let x ; let y ; let d ; 
    p.setup=()=>{

        canvas =p.createCanvas(w-50, h-50);
        canvas.style('display','block');
      // put setup code here
      t=0; 
      const x_center = (p.windowWidth - w) / 2;
      const y_center = (p.windowHeight - h) / 2;
      canvas.position(x_center, y_center);
      
    }
    p.draw = () => {
      p.background(255);
      t += .0008;
      
      for (let j = 2; x = y = j--;){  // j >0
        for (let i = w-200; d = p.noise(t - i / 99) * 3, i--; x += Math.cos(d) * 6, y += Math.sin(d) * 6, i>0){  // i >0
             j ? i - w / 2 || p.translate(-x, -y) : p.push() + p.translate(x + w / 2, y + w / 2) + p.rotate(d + Math.PI / 4) + p.line(-600, 100, 600, 100) + p.pop(i % 100 || p.scale(80));
        }  
      }
    }
}

Your initial version does not work because in instance mode translate() is a method belonging to p, and thus wants to access other methods or fields of p. The function T that you defined along the way, however, does not belong to p and thus does not have access to any this.foos.

Related