1) Use arrow keys to move circle <br />
2) Press enter when circle and line intersects! <br />
<canvas id="myCanvas" width="500" height="500"></canvas>
JavaScript
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// Geometry definitions
var centerX = 150;
var centerY = 50;
var radius = 40;
var lineX1 = 100;
var lineY1 = 150;
var lineX2 = 300;
var lineY2 = 500;
// This is the smallest move vector for circle to be tangent
var nearestVector = [0, 0];
var isPointOnSegment = false;
// resize canvas to fit window
canvas.width = window.innerWidth - 100;
canvas.height = window.innerHeight - 100;
function update() {
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
// draw geometry
// circle
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.lineWidth = 1;
context.strokeStyle = '#000000';
context.stroke();
// line
context.beginPath();
context.moveTo(lineX1, lineY1);
context.lineTo(lineX2, lineY2);
context.stroke();
// project point on line (lineStart, lineEnd, point)
var projectedPoint = projectPointOnLine([lineX1, lineY1],
[lineX2, lineY2],
[centerX, centerY]);
// is point on line (lineStart, lineEnd, point)
isPointOnSegment = isProjectedPointOnLine([lineX1, lineY1],
[lineX2, lineY2],
[projectedPoint[0], projectedPoint[1]]);
// calculate nearest vector (point1, point2, minimumDistance)
nearestVector = findNearestExitVector(projectedPoint, [centerX, centerY], radius);
// is point is on line the paint to red, otherwise green
var hilightColor = isPointOnSegment ? "red" : "green";
// Hit Point!
context.beginPath();
context.arc(projectedPoint[0], projectedPoint[1], 5, 0, 2 * Math.PI, false);
context.fillStyle = hilightColor;
context.fill();
// Line between hit-point and circle center
context.beginPath();
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.