Draw a line to follow mouse from a permanent fixed point

I would like to make 1px wide line where its point A will be in a given div, and point B will be the mouse, so when I move the mouse, the line is following along. Is this possible.
The fixed point will never change, but the variable of the mouse is what changes.

Something like the following should work, especially if you paste it into the console in this thread:

function followLine(tE) {
    let c = document.createElement('canvas')
    c.style.pointerEvents = 'none'
    c.style.position = 'absolute'
    c.style.top = 0
    c.style.left = 0
    c.width = document.documentElement.clientWidth
    c.height = document.documentElement.clientHeight

    let ctx = c.getContext('2d')
    document.body.appendChild(c)

    document.addEventListener('mousemove', e => {
         ctx.clearRect(0, 0, c.width, c.height)
         ctx.beginPath()
         let r = tE.getBoundingClientRect()
         ctx.moveTo(r.left + window.scrollX, r.top + window.scrollY)
         ctx.lineTo(e.pageX, e.pageY)
         ctx.stroke()
         ctx.closePath()
    })
}
 
[...document.querySelectorAll('.main-avatar')].map(e => followLine(e))
2 Likes

Yes Krilnon, this is brilliant…and ALMOST perfect.

The line coming from the fixed point to the mouse, is spot on. What I now need is for the line to continue through the mouse, and out the other side; as opposed to land on another fixed point.

Does that make sense? So the outer line edge, is a constantly variable position, depending on the location of the mouse on the screen.

Can share a screen shot if needed?

Looking forward to your reply!

1 Like

Hello Krilnon,

Wanted to update you on how this was resolved in the meagre possibility that others may one day also be following this thread…. So, part of your code was used to create this final function which is run on the mouse move event:

drawLine(targetLeft, targetTop) {
	// get the anchor postition
	const anchorPos = anchor.getBoundingClientRect();

	// Get the angle of the path from anchor to element
	const x = targetLeft - anchorPos.left;
	const y = targetTop - anchorPos.top;
	const ang = (Math.atan2(y, x) * 180) / Math.PI;

	// Set the new path anchor points with the angle of the first path and some math
	const x2 = targetLeft + Math.cos((Math.PI * ang) / 180) * 1000;
	const y2 = targetTop + Math.sin((Math.PI * ang) / 180) * 1000;

	// Draw the new path
	ctx.strokeStyle = "#fff";
	ctx.clearRect(0, 0, c.width, c.height);
	ctx.beginPath();
	ctx.moveTo(x2, y2);
	ctx.lineTo(anchorPos.left, anchorPos.top);
	ctx.stroke();
	ctx.closePath();
},

Thanks (see this working on https://carlrobertshaw.com/ )

1 Like

Great! Glad you found a solution for this; it fell off of my radar.

1 Like