Halfon3100
Halfon3100

Reputation: 31

Canvas - How to make line pass through a point

This is what I have right now:

How it is

I want to make it like this:

How is should be

The blue line as you can see passes through the center(400,400). The start of the blue line is not fixed, it moves according to data that the user enter.

How do I add this blue line and make it pass through the center?

Sorry for my bad English, working on that :)

Halfon

Upvotes: 1

Views: 185

Answers (2)

Shomz
Shomz

Reputation: 37701

Simply draw the line through the center point and extend its length. It's completely unclear what the length of the line is because you failed to provide any code, so I'm just doubling it in the example.

To calculate the end points, just subtract the starting x/y coordinates from the doubled x/y coordinates of the central point.

I wrote you a dynamic example which takes the mouse coordinates as a starting position, but the same principle applies if you only have a single static point from the user input. Try it here:

var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
var centerPoint;

function setSize() {
  canvas.width = canvas.offsetWidth;
  canvas.height = canvas.offsetHeight;
  centerPoint = {x: canvas.width / 2, y: canvas.height / 2};
}

canvas.addEventListener('mousemove', function(e) {
  canvas.width = canvas.width;
  context.beginPath();
  context.moveTo(e.offsetX, e.offsetY);
  context.lineTo(centerPoint.x * 2 - e.offsetX, centerPoint.y * 2 - e.offsetY);
  context.lineWidth = 3;
  context.strokeStyle = '#0000ff';
  context.stroke();
})

canvas.addEventListener('mousedown', function(e) {
  centerPoint = {x: e.offsetX, y: e.offsetY};
  canvas.width = canvas.width;
})

window.addEventListener('resize', setSize);
setSize()
canvas {width: 100%;height: 100%;position: absolute;}
body {margin: 0}
p {position: absolute; pointer-events: none}
<canvas id="c"></canvas>
<p>Click anywhere to set the center point (dead center by default)</p>

Upvotes: 2

John Bupit
John Bupit

Reputation: 10618

Use mathematics.

Let the center co-ordinates be (Cx, Cy), which in your case are (400, 400). Let the user's co-ordinates be (Ux, Uy).

The equation of the line passing through the center from (Ux, Uy) would be given by the equation:

y - Cy = slope * (x - Cx), where slope = (Cy - Uy) / (Cx - Ux).

Now, to draw the line from Ux to some x co-ordinate, say Px, simply use the equation to calculate Py = Slope * (Px - Cx) + Cy, then draw the line from (Ux, Uy) to (Px, Py).

context.beginPath();
context.moveTo(Ux, Uy);
context.lineTo(Px, Py);
context.stroke();

Upvotes: 4

Related Questions