JSFiddle - React, Tailwind, and code Playground
by Darby Rathbone
CSS
canvas{
position:absolute;
top:50%;
left:50%;
border:solid 1px black;
}
JavaScript
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = canvas.height = 100;
document.body.appendChild(canvas);
ctx.translate(50,50);
var thispos = getOffset(canvas);
window.onmousemove=function(e){
ctx.clearRect(-50,-50,100,100);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.save();
ctx.rotate(Math.atan2(e.clientY-(thispos.top+50),e.clientX-(thispos.left+50)));
ctx.lineTo(50,0);
ctx.stroke();
ctx.restore();
};
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}