KodyJH
KodyJH

Reputation: 115

How to scale co-ordinates to fit on canvas?

I'm having trouble scale x and y co-ordinates that are being loaded in from a .txt files to my canvas size so the circles and lines I've drawn don't extend beyond the canvas, any suggestions?

let dots = [];
let dotsData;
let orderData;
function preload() {
  dotsData = loadStrings('./dots.txt');
  orderData = loadStrings('./orderFile.txt');
}

function setup() {
  createCanvas(750, 750);
  createDots(dotsData);
}

function draw() {
  background(220);
  fill(255, 100, 200);
  
  
  for (let i = 0; i < dots.length; i++) {
     circle(dots[i].x, dots[i].y, 20);
     let goalDot = dots.find(e => e.id == orderData[i]);
     if (goalDot) {
       line(dots[i].x, dots[i].y, goalDot.x, goalDot.y);
     }
  }
}

function createDots(filename) {
  const probData = new Array(filename.length);
  for (let i = 0; i < probData.length; i++) {
    dotsData[i] = splitTokens(filename[i]);
    dots.push({
      id: dotsData[i][0],
      x: dotsData[i][1],
      y: dotsData[i][2]
    })
  }
}

The dotsData file looks like

1 565.0 575.0
2 25.0 185.0
3 345.0 750.0
4 945.0 685.0
5 845.0 655.0

The orderData file looks like this

5
1
4
3
2

Upvotes: 1

Views: 50

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

Compute the maximum coordinates of the geometry (points), after reading from file:

let max_x = 0;
let max_y = 0;

function createDots(filename) {
    const probData = new Array(filename.length);
    for (let i = 0; i < probData.length; i++) {
        dotsData[i] = splitTokens(filename[i]);
        dots.push({
            id: dotsData[i][0],
            x: dotsData[i][1],
            y: dotsData[i][2]
        })
        max_x = max(max_x, dotsData[i][1]);
        max_y = max(max_y, dotsData[i][2]);
    }
}

Before drawing, set a scale() depending on the width and the height of the canvas:

function draw() {
    background(220);
    fill(255, 100, 200);
    
    scale(width / (max_x * 1.1), height / (max_y * 1.1));
    
    for (let i = 0; i < dots.length; i++) {
        circle(dots[i].x, dots[i].y, 20);
        let goalDot = dots.find(e => e.id == orderData[i]);
        if (goalDot) {
            line(dots[i].x, dots[i].y, goalDot.x, goalDot.y);
        }
    }
}

Upvotes: 1

Related Questions