获取2点之间的所有像素坐标 [英] Get all pixel coordinates between 2 points

查看:482
本文介绍了获取2点之间的所有像素坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一条直线上获得2个给定点之间的所有x,y坐标. 尽管这似乎是一件容易的事,但我似乎无法解决这个问题.

I want to get all the x,y coordinates between 2 given points, on a straight line. While this seems like such an easy task, I can't seem to get my head around it.

例如,

  • 第1点:(10,5)
  • 第2点:(15,90)

推荐答案

编辑:以下解决方案仅在几何角度上适用.在屏幕上绘图与理论几何图形不同,您应该听人们建议使用Bresenham算法.

The solution below only applies from a geometrical point of view. Drawing on a screen is different than theoretical geometry, you should listen to the people suggesting Bresenham's algorithm.

给出两点,并知道直线的方程为y = m*x + b,其中m为斜率,b为截距,则可以计算mb,然后将方程应用于所有您的A点和B点之间的X轴值:

Given, two points, and knowing that the line's equation is y = m*x + b, where m is the slope and b the intercept, you can calculate m and b and then apply the equation to all the values of the X axis between your A and B points:

var A = [10, 5];
var B = [15, 90];

function slope(a, b) {
    if (a[0] == b[0]) {
        return null;
    }

    return (b[1] - a[1]) / (b[0] - a[0]);
}

function intercept(point, slope) {
    if (slope === null) {
        // vertical line
        return point[0];
    }

    return point[1] - slope * point[0];
}

var m = slope(A, B);
var b = intercept(A, m);

var coordinates = [];
for (var x = A[0]; x <= B[0]; x++) {
    var y = m * x + b;
    coordinates.push([x, y]);
}

console.log(coordinates); // [[10, 5], [11, 22], [12, 39], [13, 56], [14, 73], [15, 90]]

这篇关于获取2点之间的所有像素坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆