Last active
January 21, 2026 16:17
-
-
Save scharfie/b038a77c9cc6ed3b1b05310f888e45c0 to your computer and use it in GitHub Desktop.
mouse crosshair
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // example: https://jsfiddle.net/h4gbru7o/ | |
| function InstallMouseCrossHair() { | |
| const color = "#333"; | |
| const size = 24; | |
| const sizePx = size + 'px'; | |
| const sizeHalf = size > 1 ? size / 2 : 0; | |
| const xOffset = 0; | |
| const yOffset = 0; | |
| let frameRequested = false; | |
| const xBar = document.createElement('div'); | |
| const yBar = document.createElement('div'); | |
| const container = document.createElement('div'); | |
| Object.assign(xBar.style, { visibility: 'hidden', background: color, position: 'fixed', width: '100%', height: sizePx }); | |
| Object.assign(yBar.style, { visibility: 'hidden', background: color, position: 'fixed', width: sizePx, height: '100%' }); | |
| Object.assign(container.style, { opacity: 0.6, position: 'fixed', top: 0, left: 0, 'mix-blend-mode': 'difference' }); | |
| container.appendChild(xBar); | |
| container.appendChild(yBar); | |
| document.body.appendChild(container); | |
| function toggleVisibility(event) { | |
| // only show the crosshair when CTRL key is pressed | |
| let visibility = event.ctrlKey ? 'visible' : 'hidden'; | |
| xBar.style.visibility = visibility; | |
| yBar.style.visibility = visibility; | |
| }; | |
| function handleMove(event) { | |
| // we don't want to queue up multiple animation frame requests | |
| if (frameRequested) { return; } | |
| frameRequested = true; | |
| let x = event.clientX - sizeHalf + xOffset; | |
| let y = event.clientY - sizeHalf + yOffset; | |
| window.requestAnimationFrame(() => { | |
| xBar.style.transform = `translateY(${y}px)`; | |
| yBar.style.transform = `translateX(${x}px)`; | |
| frameRequested = false; | |
| }); | |
| } | |
| window.addEventListener('keydown', toggleVisibility); | |
| window.addEventListener('keyup', toggleVisibility); | |
| window.addEventListener('mousemove', handleMove); | |
| } | |
| window.addEventListener('DOMContentLoaded', InstallMouseCrossHair); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment