JSFiddle - React, Tailwind, and code Playground
by Bretto
HTML
<div id="canvas"></div>
<div id="pointer"></div>
<div id="intructions">The black dot's movement should be constrained to the gray circle</div>
CSS
html, body {
height: 100%;
}
#canvas {
background: #eee;
position: absolute;
height: 300px;
width: 300px;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -150px;
-webkit-border-radius: 300px;
-moz-border-radius: 300px;
border-radius: 300px;
border: dashed #ccc 1px;
}
#pointer {
position: absolute;
background: #000;
width: 20px;
height: 20px;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px;
margin-top: -10px;
margin-left: -10px;
top: 50%;
left: 50%;
}
#intructions {
position: absolute;
bottom: 0;
text-align: center;
padding-bottom: 10px;
width: 100%;
}
JavaScript
var pointerEl = document.getElementById("pointer");
var canvasEl = document.getElementById("canvas");
var canvas = {
width: canvasEl.offsetWidth,
height: canvasEl.offsetHeight,
top: canvasEl.offsetTop,
left: canvasEl.offsetLeft
};
canvas.center = {x: canvas.left + canvas.width / 2, y:canvas.top + canvas.height / 2};
canvas.radius = canvas.width / 2;
window.onmousemove = function(e) {
var result = limit(e.x, e.y);
pointer.style.left = result.x + "px";
pointer.style.top = result.y + "px";
}
function limit(x, y) {
// the vector between the two points
var dx = x - canvas.center.x ,
dy = y - canvas.center.y,
distanceSquared = (dx*dx) +(dy*dy);
if (distanceSquared <= canvas.radius*canvas.radius) {
return {x: x, y: y};
}
else {
var distance = Math.sqrt(distanceSquared),
ratio = canvas.radius/distance;
return {
x: (dx*ratio)+canvas.center.x,
y: (dy*ratio)+canvas.center.y
}
}
}