Last active
April 19, 2019 17:14
-
-
Save okiwan/4c8e9941426c47a2463b27aa59ff6167 to your computer and use it in GitHub Desktop.
Draw a trail following mouse move
This file contains 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
/** | |
* This is just the JavaScript side, so an HTML must be created with a canvas element. | |
* Originally published by @NoahYamamoto | |
*/ | |
function StartMouseTrail() { | |
const canvas = document.getElementById("canvas"); | |
const ctx = canvas.getContext("2d"); | |
// Get proper height and width for canvas, then set resize handler. | |
canvas.width = window.innerWidth; | |
canvas.height = window.innerHeight; | |
window.addEventListener( | |
"resize", | |
({ target: { innerWidth, innerHeight } }) => { | |
canvas.width = innerWidth; | |
canvas.height = innerHeight; | |
}, | |
false | |
); | |
const startAnimation = () => { | |
// Use a closure here to keep internal state. | |
let lastX = 0; | |
let lastY = 0; | |
let currX = 0; | |
let currY = 0; | |
const update = () => { | |
ctx.beginPath(); | |
ctx.lineWidth = 7; | |
ctx.moveTo(lastX, lastY); | |
ctx.lineTo(currX, currY); | |
ctx.strokeStyle = "#b200f0"; | |
ctx.stroke(); | |
lastX = currX; | |
lastY = currY; | |
// Fade out the previous tails | |
ctx.fillStyle = `rgba(0, 0, 0, 0.1)`; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
// Request an animation frame to update it for a smooth 60fps independent of mousemove updates. | |
requestAnimationFrame(update); | |
}; | |
// On mouse move update cursor position. | |
window.addEventListener( | |
"mousemove", | |
({ pageX, pageY }) => { | |
currX = pageX; | |
currY = pageY; | |
}, | |
false | |
); | |
// Start the update cycle. | |
update(); | |
}; | |
startAnimation(); | |
} | |
StartMouseTrail() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment