【问题标题】:How to scale co-ordinates to fit on canvas?如何缩放坐标以适合画布?
【发布时间】:2021-09-30 03:46:15
【问题描述】:

我无法将 x 和 y 坐标从 .txt 文件加载到我的画布大小,因此我绘制的圆圈和线条不会超出画布,有什么建议吗?

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]
    })
  }
}

dotsData 文件的样子

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

orderData 文件如下所示

5
1
4
3
2

【问题讨论】:

    标签: javascript processing p5.js


    【解决方案1】:

    从文件读取后计算几何(点)的最大坐标:

    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]);
        }
    }
    

    在绘制之前,根据画布的widthheight设置一个scale()

    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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-31
      • 2011-12-28
      • 2014-08-27
      • 2016-09-30
      • 2016-01-01
      • 1970-01-01
      • 2016-11-11
      • 2012-03-07
      • 2016-10-29
      相关资源
      最近更新 更多