Get all pixel coordinates between 2 points - javascript

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.
So, for example:
Point 1: (10,5)
Point 2: (15,90)

Edit: 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.
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]]

Given the point A(10, 5) and B(15, 90) and C(x, y) in AB we have:
(x - 10) / (y - 5) = (15 - 10) / (90 - 5)
What you can do is to iterate from x=10 to x=15 and calculate the corresponding y. Since x and y are integers, some times you have to round the result (or skip it).

Based on the wiki article, here's my JS code which handles both high and low lines:
const drawLine = (x0, y0, x1, y1) => {
const lineLow = (x0, y0, x1, y1) => {
const dx = x1 - x0
let dy = y1 - y0
let yi = 1
if (dy < 0) {
yi = -1
dy = -dy
}
let D = 2 * dy - dx
let y = y0
for (let x = x0; x < x1; x++) {
drawPoint(x, y)
if (D > 0) {
y = y + yi
D = D - 2 * dx
}
D = D + 2 * dy
}
}
const lineHigh = (x0, y0, x1, y1) => {
let dx = x1 - x0
const dy = y1 - y0
let xi = 1
if (dx < 0) {
xi = -1
dx = -dx
}
let D = 2 * dx - dy
let x = x0
for (let y = y0; y < y1; y++) {
drawPoint(x, y)
if (D > 0) {
x = x + xi
D = D - 2 * dy
}
D = D + 2 * dx
}
}
const { abs } = Math
if (abs(y1 - y0) < abs(x1 - x0)) {
if (x0 > x1) {
lineLow(x1, y1, x0, y0)
} else {
lineLow(x0, y0, x1, y1)
}
} else {
if (y0 > y1) {
lineHigh(x1, y1, x0, y0)
} else {
lineHigh(x0, y0, x1, y1)
}
}
}

Related

Algoritma DDA (Digital Diferential Analyzer)

I have a program in JavaScript, but I can't display the graph points like (2,1), (3,2), (4,2), (5,3), (6,4), (7,4), (8,5).
function dda(x1, y1, x2, y2) {
var dx = x2 - x1;
var dy = y2 - y1;
if (Math.abs(dx) > Math.abs(dy)) {
var step = Math.abs(dx);
} else {
var step = Math.abs(dy);
}
var x_inc = dx / step;
var y_inc = dy / step;
var x = x1;
var y = y1;
for (var k = 1; k < step; k++) {
x = x + x_inc;
y = y + y_inc; //I'm confused about this part
}
return x;
}
console.log(dda(2, 1, 8, 5));
You need to collect x and y values.
Beside this, you need to start with k = 0 and increment the values after using the values.
function dda(x1, y1, x2, y2) {
const
dx = x2 - x1,
dy = y2 - y1,
step = Math.abs(dx) > Math.abs(dy)
? Math.abs(dx)
: Math.abs(dy),
x_inc = dx / step,
y_inc = dy / step,
result = [];
for (let k = 0, x = x1, y = y1; k < step; k++) {
result.push([x, y]);
x += x_inc;
y += y_inc;
}
return result;
}
console.log(dda(2, 1, 8, 5));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Reflection end point of intersecting two lines

How do I calculate the bounced end point of intersecting two lines?
When given the following two lines, I was able to calculate intersection point of two lines with the following function.
export function intersection(line1, line2) {
line1.y1 *= -1; line1.y2 *= -1; // for Webpage coordinates
line2.y3 *= -1; line2.y4 *= -1; // for Webpage coordinates
const [x1, y1, x2, y2] = line1;
const [x3, y3, x4, y4] = line2;
const [a1, b1, c1] = [y2 - y1, x1 - x2, x2 * y1 - x1 * y2];
if ( a1 === 0 && b1 === 0 ) return 'line1 does not have length';
const [a2, b2, c2] = [y4 - y3, x3 - x4, x4 * y3 - x3 * y4];
if ( a2 === 0 && b2 === 0 ) return 'line2 does not have length';
const denom = a1 * b2 - a2 * b1;
if (denom === 0) return 'lines are parallel';
const x = (b1 * c2 - b2 * c1) / denom; // (x,y) is the intersection
const y = (a2 * c1 - a1 * c2) / denom;
// check if two lines are actually crossing w/o extending it
function getDist(x1, y1, x2, y2) {
return Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
}
const distLine1 = getDist(x1, y1, x2, y2);
const distLine2 = getDist(x3, y3, x4, y4);
const distToXY1 = Math.max(getDist(x1, y1, x, y), getDist(x2, y2, x, y)) ;
const distToXY2 = Math.max(getDist(x3, y3, x, y), getDist(x4, y4, x, y)) ;
if (distToXY1 > distLine1 || distToXY2 > distLine2)
return 'lines does not meet';
return {x, y};
}
DEMO: https://stackblitz.com/edit/intersection-of-two-lines?file=index.js
However, I am struggling to find a bounced-off position(or reflection point) of two lines using two lines.
What's the formula of getting x/y position from line1(x1, x2, y1, y2) and line2(x1, x2, y1, y2)?
You have to split the part of the red vector that's "inside the wall" into two components, one parallel to the wall, the other perpendicular to it. Then you negate the perpendicular component and add them back together.
class Line {
constructor(x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.dx = x2 - x1;
this.dy = y2 - y1;
}
intersect(o) {
const d = this.dy * o.dx - this.dx * o.dy;
if (d === 0) return null; // parallel
const k = ((o.y1 - this.y1) * o.dx + (this.x1 - o.x1) * o.dy) / d;
return {
x: this.x1 + k * this.dx,
y: this.y1 + k * this.dy
};
}
bounce(o) {
const i = this.intersect(o);
if (!i) return null;
// vector from intersection to end
const v = {
x: this.x2 - i.x,
y: this.y2 - i.y
};
// split v into two perpendicular vectors, one parallel to o
// the perpendicular one is o's direction rotated by 90°
const p = { x: o.dy, y: -o.dx };
// v.x = a * o.dx + b * p.x
// v.y = a * o.dy + b * p.y
// division by zero is impossible since o and p are perpendicular
const a = (v.y * p.x - v.x * p.y) / (o.dy * p.x - o.dx * p.y);
const b = (v.y * o.dx - v.x * o.dy) / (p.y * o.dx - p.x * o.dy);
// negate b to mirror end of line on o
return {
x: i.x + a * o.dx - b * p.x,
y: i.y + a * o.dy - b * p.y
}
}
}
const l1 = new Line(100, 300, 400, 100);
const l2 = new Line(100, 100, 400, 300);
console.log(l1.bounce(l2));
I think I am close to an answer.
This is my approach
get a perpendicular meeting point from the intersection and end of line2.
Make a line(start: end of line2, end: perpendicular meeting point), then extend the line double amount to get the endpoint.
https://stackblitz.com/edit/intersection-of-two-lines-nes7zy?view=preview
In the demo, this approach looks fine, If a math expert can confirm this approach, it would be appreciated.
// https://stackoverflow.com/a/1811636/454252
function getPerpendicularPoint(iPoint, line1, line2) {
const [x1, y1] = [iPoint.x, iPoint.y]; // start point
const [x2, y2] = [line1[2], line1[3]]; // baseline end point
const [x3, y3] = [line2[2], line2[3]]; // extended line end point
const k = ((y2-y1) * (x3-x1) - (x2-x1) * (y3-y1)) / ((y2-y1)**2 + (x2-x1)**2);
const x4 = x3 - k * (y2-y1);
const y4 = y3 + k * (x2-x1);
return {x: x4, y: y4};
}
//http://www.java2s.com/Tutorials/Javascript/Canvas_How_to/Shape/Extend_a_line_before_and_after_original_endpoints.htm
function getExtendedPoint(startPt, endPt, extent) {
var dx = endPt.x - startPt.x;
var dy = endPt.y - startPt.y;
var x = startPt.x + dx * extent;
var y = startPt.y + dy * extent;
return {x, y};
}
let line1 = [100, 100, 400, 300];
let line2 = [100, 300, 400, 100];
const iPoint = {x: 250, y: 200}; // intersection(line1, line2);
const pPoint = getPerpendicularPoint(iPoint, line1, line2);
const ePoint = getExtendedPoint({x:line2[2], y:line2[3]}, pPoint, 2);
console.log(pPoint, ePoint);

Is this code for determining if a circle and line SEGMENT intersects correct?

It's apparently very hard to find the answer to whether a line segment and circle intersect. For example, if you google you'll find this question and even the top two answers seem wrong.
The accepted answer has a comment saying: This seems to compute the intersection of a circle with a line, not a segment Scroll down to the next answer and you'll find another comment saying Isn't this answer in incomplete? It finds whether a circle and line intersect, not a line segment.
I've then tried to search for a function for determining if just a segment intersects a circle, but to no avail. The best I could find is a pseudocode explanation here.
I've tried to adapt his code and while it seems to work, it seems overly verbose and I'm not sure if my implementation is correct. I'm asking whether or not this is correct and if it is, is there indeed no better way of determining this? What is the ideal way of determining if a line segment and circle intersects? Please note, I only need to know if they intersect, not where they intersect.
I've provided a full demo reproduction below so you can also visualize it.
function lineSegmentIntersectsCircle(x1, y1, x2, y2, cx, cy, r) {
let deltaX = x2 - x1;
let deltaY = y2 - y1;
let mag = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
let unitX = deltaX / mag;
let unitY = deltaY / mag;
let d = (cx - x1) * unitY - (cy - y1) * unitX;
if (d < -r || d > r) { return false; }
let x1CXDelta = x1 - cx;
let y1CYDelta = y1 - cy;
let x2CXDelta = x2 - cx;
let y2CYDelta = y2 - cy;
let pointOneWithinCircle = x1CXDelta * x1CXDelta + y1CYDelta * y1CYDelta < r * r;
if (pointOneWithinCircle) { return true; }
let pointTwoWithinCircle = x2CXDelta * x2CXDelta + y2CYDelta * y2CYDelta < r * r;
if (pointTwoWithinCircle) { return true; }
let foo = unitX * x1 + unitY * y1;
let bar = unitX * cx + unitY * cy;
let baz = unitX * x2 + unitY * y2;
return (foo < bar && bar < baz) || (baz < bar && bar < foo);
}
let ctx = document.querySelector("canvas").getContext("2d");
function drawCircle(xCenter, yCenter, radius) {
ctx.beginPath();
ctx.arc(xCenter, yCenter, radius, 0, 2 * Math.PI);
ctx.fill();
}
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
let circleX = 340;
let circleY = 250;
let circleR = 60;
let lineX1 = 50;
let lineY1 = 350;
let lineX2 = 285;
let lineY2 = 250;
draw = () => {
ctx.fillStyle = "#b2c7ef";
ctx.fillRect(0, 0, 800, 800);
ctx.fillStyle = "#ffffff";
drawCircle(circleX, circleY, circleR);
drawLine(lineX1, lineY1, lineX2, lineY2);
}
console.log(lineSegmentIntersectsCircle(lineX1, lineY1, lineX2, lineY2, circleX, circleY, circleR))
draw();
canvas { display: flex; margin: 0 auto; }
<canvas width="400" height="400"></canvas>
I think it would be a simpler to (1) compute the line-disk intersection, which is either empty, a point, or a line segment (2) test whether the intersection intersects the line segment.
The points of the line are ((1-t) x1 + t x2, (1-t) y1 + t y2) for all real t. Let x(t) = (1-t) x1 + t x2 - cx and y(t) = (1-t) y1 + t y2 - cy. The line-disk intersection is nonempty if and only if the polynomial x(t)^2 + y(t)^2 - r^2 = 0 has real roots t1 <= t2. In this case, the line-disk intersection is all t in [t1, t2]. The line segment is all t in [0, 1]. The two intersect if and only if t1 <= 1 and t2 >= 0.
Computing t1 and t2 requires a square root, which we can avoid. Let a, b, c be such that x(t)^2 + y(t)^2 - r^2 = a t^2 + b t + c. We have t1 + t2 = -b/a and t1 t2 = c/a.
The roots t1 and t2 are real if and only if b^2 - 4 a c >= 0.
The condition t1 <= 1 is false if and only if t1 - 1 > 0 and t2 - 1 > 0, which in turn is true if and only if (t1 - 1) + (t2 - 1) > 0 and (t1 - 1) (t2 - 1) > 0, which is equivalent to -b/a - 2 > 0 and c/a + b/a + 1 > 0. Since a > 0, this simplifies to -b > 2 a and c + b + a > 0.
The condition t2 >= 0 is false if and only if t1 < 0 and t2 < 0, which in turn is true if and only if t1 + t2 = -b/a < 0 and t1 t2 = c/a > 0. Since a > 0, this simplifies to b > 0 and c > 0.
Implementation in Javascript.
function lineSegmentIntersectsCircleOptimized(x1, y1, x2, y2, cx, cy, r) {
let x_linear = x2 - x1;
let x_constant = x1 - cx;
let y_linear = y2 - y1;
let y_constant = y1 - cy;
let a = x_linear * x_linear + y_linear * y_linear;
let half_b = x_linear * x_constant + y_linear * y_constant;
let c = x_constant * x_constant + y_constant * y_constant - r * r;
return (
half_b * half_b >= a * c &&
(-half_b <= a || c + half_b + half_b + a <= 0) &&
(half_b <= 0 || c <= 0)
);
}
function lineSegmentIntersectsCircle(x1, y1, x2, y2, cx, cy, r) {
let deltaX = x2 - x1;
let deltaY = y2 - y1;
let mag = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
let unitX = deltaX / mag;
let unitY = deltaY / mag;
let d = (cx - x1) * unitY - (cy - y1) * unitX;
if (d < -r || d > r) {
return false;
}
let x1CXDelta = x1 - cx;
let y1CYDelta = y1 - cy;
let x2CXDelta = x2 - cx;
let y2CYDelta = y2 - cy;
let pointOneWithinCircle =
x1CXDelta * x1CXDelta + y1CYDelta * y1CYDelta < r * r;
if (pointOneWithinCircle) {
return true;
}
let pointTwoWithinCircle =
x2CXDelta * x2CXDelta + y2CYDelta * y2CYDelta < r * r;
if (pointTwoWithinCircle) {
return true;
}
let foo = unitX * x1 + unitY * y1;
let bar = unitX * cx + unitY * cy;
let baz = unitX * x2 + unitY * y2;
return (foo < bar && bar < baz) || (baz < bar && bar < foo);
}
function test() {
for (let i = 0; i < 10000000; i++) {
let x1 = Math.random();
let y1 = Math.random();
let x2 = Math.random();
let y2 = Math.random();
let cx = Math.random();
let cy = Math.random();
let r = Math.random();
if (
lineSegmentIntersectsCircle(x1, y1, x2, y2, cx, cy, r) !=
lineSegmentIntersectsCircleOptimized(x1, y1, x2, y2, cx, cy, r)
) {
console.log("bad");
break;
}
}
}
test();

Javascript Midpoint Line Drawing Algorithm

I'm drawing a line in javascript using the Midpoint Algorithm Line Drawing.
When the line is in a descent trajectory, it computes the wrong values.
Can somebody help me?
data input
//midline(1,6,8,4);
function midline(x0, y0, x1, y1) {
/* Using midpoint algorithm for lines. */
const dx = x1 - x0;
const dy = y1 - y0;
var d = 2 * dy - dx;
const incrE = 2 * dy;
const incrNE = 2 * (dy - dx);
var x = x0;
var y = y0;
var output = [];
//listeners
console.log("dy = ", dy, "dx = ", dx);
console.log("d = ", d);
console.log("incrE = ", incrE);
console.log("incrNE = ", incrNE);
console.log("----------------------------------");
while (x <= x1) {
// if not the last x
console.log("x = ", x, " y = ", y);
output.push([x,y]);
if (d <= 0) {
console.log("E");
d = d + incrE;
x++;
} else {
console.log("NE");
d = d + incrNE;
x++;
y++;
}
}
console.table(output);
}
If per my comment the Mid Point Line Drawing algorithm is only suited for the first quadrant, that is...
x0 < x1 and y0 < y1
...must hold true, then adjustments are required if x1 < x0 or y1 < y0.
Taking the case presented (1,6) - (8,4), this is a downward slope because y1 < y0 (ie, 4 < 6 ). To make this a workable case for the Mid Point Line Drawing algorithm, you can simply negate the y values, in which case y0 < y1 will then hold true. Of course, when capturing the results, the values need to then be adjusted by multiplying by -1 again. So, suggest wedging in the following before putting x0, y0, x1, and y1 to use...
let xReflect = 1;
if ( x1 < x0 ) {
x0 = -x0;
x1 = -x1;
xReflect = -1;
}
let yReflect = 1;
if ( y1 < y0 ) {
y0 = -y0;
y1 = -y1;
yReflect = -1;
}
...and then, when pushing the output to the array, you will need to perform the following...
output.push( [ x * xReflect, y * yReflect ] );
Hope this helps.

Collision detection between a line and a circle in JavaScript

I'm looking for a definitive answer, maybe a function cos I'm slow, that will determine if a line segment and circle have collided, in javascript (working with canvas)
A function like the one below that simply returns true if collided or false if not would be awesome. I might even donate a baby to you.
function isCollided(lineP1x, lineP1y, lineP2x, lineP2y, circlex, circley, radius) {
...
}
I've found plenty of formulas, like this one, but they are over my head.
Here you will need some Math:
This is the basic concept if you don't know how to solve equations in general. I will leave the rest of the thinking to you. ;) Figuring out CD's length isn't that hard.
If you are asking how, that's how:
Finding collisions in JavaScript is kind of complicated.
I Spent about a day and a half to make it perfect.. Hope this helps.
function collisionCircleLine(circle,line){ // Both are objects
var side1 = Math.sqrt(Math.pow(circle.x - line.p1.x,2) + Math.pow(circle.y - line.p1.y,2)); // Thats the pythagoras theoram If I can spell it right
var side2 = Math.sqrt(Math.pow(circle.x - line.p2.x,2) + Math.pow(circle.y - line.p2.y,2));
var base = Math.sqrt(Math.pow(line.p2.x - line.p1.x,2) + Math.pow(line.p2.y - line.p1.y,2));
if(circle.radius > side1 || circle.radius > side2)
return true;
var angle1 = Math.atan2( line.p2.x - line.p1.x, line.p2.y - line.p1.y ) - Math.atan2( circle.x - line.p1.x, circle.y - line.p1.y ); // Some complicated Math
var angle2 = Math.atan2( line.p1.x - line.p2.x, line.p1.y - line.p2.y ) - Math.atan2( circle.x - line.p2.x, circle.y - line.p2.y ); // Some complicated Math again
if(angle1 > Math.PI / 2 || angle2 > Math.PI / 2) // Making sure if any angle is an obtuse one and Math.PI / 2 = 90 deg
return false;
// Now if none are true then
var semiperimeter = (side1 + side2 + base) / 2;
var areaOfTriangle = Math.sqrt( semiperimeter * (semiperimeter - side1) * (semiperimeter - side2) * (semiperimeter - base) ); // Heron's formula for the area
var height = 2*areaOfTriangle/base;
if( height < circle.radius )
return true;
else
return false;
}
And that is how you do it..
Matt DesLauriers published a Javascript library for this problem at https://www.npmjs.com/package/line-circle-collision. The API is straightforward:
var circle = [5, 5],
radius = 25,
a = [5, 6],
b = [10, 10]
var hit = collide(a, b, circle, radius)
function pointCircleCollide(point, circle, r) {
if (r===0) return false
var dx = circle[0] - point[0]
var dy = circle[1] - point[1]
return dx * dx + dy * dy <= r * r
}
var tmp = [0, 0]
function lineCircleCollide(a, b, circle, radius, nearest) {
//check to see if start or end points lie within circle
if (pointCircleCollide(a, circle, radius)) {
if (nearest) {
nearest[0] = a[0]
nearest[1] = a[1]
}
return true
} if (pointCircleCollide(b, circle, radius)) {
if (nearest) {
nearest[0] = b[0]
nearest[1] = b[1]
}
return true
}
var x1 = a[0],
y1 = a[1],
x2 = b[0],
y2 = b[1],
cx = circle[0],
cy = circle[1]
//vector d
var dx = x2 - x1
var dy = y2 - y1
//vector lc
var lcx = cx - x1
var lcy = cy - y1
//project lc onto d, resulting in vector p
var dLen2 = dx * dx + dy * dy //len2 of d
var px = dx
var py = dy
if (dLen2 > 0) {
var dp = (lcx * dx + lcy * dy) / dLen2
px *= dp
py *= dp
}
if (!nearest)
nearest = tmp
nearest[0] = x1 + px
nearest[1] = y1 + py
//len2 of p
var pLen2 = px * px + py * py
//check collision
return pointCircleCollide(nearest, circle, radius)
&& pLen2 <= dLen2 && (px * dx + py * dy) >= 0
}
var circle = [5, 5],
radius = 25,
a = [5, 6],
b = [10, 10]
var hit = lineCircleCollide(a, b, circle, radius)

Categories

Resources