Samuel Pollard
Samuel Pollard

Reputation: 23

Graph not being plot

I have built a JavaScript P5.js program to plot graphs. Everything works apart from the points do not appear on the display, and when they do they don't follow the trend the graph should.

function setup() {
  H = 800;
  W = 800;
  wFreq = 20;
  hFreq = 20;
  wDist = H / hFreq;
  hDist = W / wFreq;
  uLength = 10;
  
  createCanvas(W, H);
}

function formula(x) {
  return x*x
}

function draw() {
  background(220);
  translate(0, 0)
  
  rect(0, H/2, W, 0);
  rect(W/2, 0, 0, H);
  
  translate(0, H/2);
  for(i = W/2; i -= 1; i > 0) {
    rect((i-0.5) * wDist /2, -uLength/2, 0, uLength);
  }
  
  translate(W/2, -H);
  for(i = H/2; i -= 1; i > 0) {
    rect(-uLength/2,i * (hDist -1) /(4*(10/hFreq)), uLength, 0);
  }
  
  translate(200, 200);
  for(i = -wFreq; i += 1; i < wFreq) {
      rect(i*wDist, formula(i), 1, 1);
  }
}

Upvotes: 0

Views: 45

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42174

Note that your calls to translate() stack.

I'm not sure exactly where you want your points to show up, but to help you debug, I can see the points if I change your translate(200, 200); call to translate(400, 400); instead.

You'll have to play with the values you pass in to achieve the effect you want. You also might want to look up the push() and pop() functions in the reference.

You might also consider not using translate() at all, and using the coordinates directly in your drawing code.

Upvotes: 1

Related Questions