在p5js中绘制平滑线



我创建了一个函数,它从第一个参数的坐标到第二个参数的坐标画一条线。代码使用鼠标坐标作为函数的参数来运行函数。但是,我有一个问题,垂直移动鼠标光标会导致线不均匀。

let circles = [];
function setup() {
  createCanvas(600, 600);
}
function draw() {
  lineCreate([pmouseX,pmouseY],[mouseX,mouseY])
  
}
function lineCreate(point1, point2) {
  length = sqrt(pow(point2[0]-point1[0],2) + pow(point2[1]-point1[1],2))
  slope = (point2[1]-point1[1])/(point2[0]-point1[0])
  x = min(point1[0],point2[0])
  endX = max(point1[0],point2[0])
  for (let i = x; i < endX; i++) {
    pointSlope = slope*(i - point1[0]) + point1[1]
    circle(i,pointSlope,2,2)
  }
}

你需要用线连接点:

function setup() {
    createCanvas(600, 600);
    strokeWeight(4);
    noFill();
    rect(2, 2, 596, 596);
}
function draw() {
    line(pmouseX, pmouseY, mouseX,mouseY)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

如果您想用单个点绘制直线,则需要区分点之间的距离沿x轴还是y轴较大:

function setup() {
    createCanvas(600, 600);
    strokeWeight(4);
    noFill();
    rect(2, 2, 596, 596);
    fill(0);
}
function draw() {
    lineCreate([pmouseX,pmouseY], [mouseX,mouseY])  
}
function lineCreate(point1, point2) {
    x0 = point1[0];
    x1 = point2[0];
    y0 = point1[1];
    y1 = point2[1];
    if (abs(x1 - x0) > abs(y1 - y0)) {
        if (x0 > x1) {
            let t = x0; x0 = x1; x1 = t;
            t = y0; y0 = y1; y1 = t;
        }
        for (let x = x0; x <= x1; x++) {
            let y = y0 + (y1-y0) * (x-x0) / (x1-x0);
            circle(x, y, 2);
        }
    } else {
        if (y0 > y1) {
            let t = x0; x0 = x1; x1 = t;
            t = y0; y0 = y1; y1 = t;
        }
        for (let y = y0; y <= y1; y++) {
            let x = x0 + (x1-x0) * (y-y0) / (y1-y0);
            circle(x, y, 2);
        }
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

最新更新