Skip to content

Instantly share code, notes, and snippets.

@deslee
Created February 28, 2019 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deslee/74fb50b3e3d30da07cab9665c0038b3e to your computer and use it in GitHub Desktop.
Save deslee/74fb50b3e3d30da07cab9665c0038b3e to your computer and use it in GitHub Desktop.
import React, { useState, useEffect, useRef } from 'react';
const states = {
PromptUserToMovePointer: "Move your cursor around",
PromptUserToHoldStill: "Hold still!",
DisplayingCat: "Displaying cat..."
}
export default ({ }) => {
const [uiState, setUiState] = useState(states.PromptUserToMovePointer)
const [pointerPos, setPointerPos] = useState()
var waitOnMouseTimeout = null
const onMouseMove = (e) => {
e.persist()
setUiState(states.PromptUserToHoldStill);
if (waitOnMouseTimeout) clearTimeout(waitOnMouseTimeout)
waitOnMouseTimeout = setTimeout(() => {
// the user was still for the necessary duration
if (uiState == states.PromptUserToHoldStill) {
setUiState(states.DisplayingCat)
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left; //x position within the element.
var y = e.clientY - rect.top; //y position within the element.
setPointerPos([x, y])
}
}, 1000)
}
const onMouseLeave = () => {
if (waitOnMouseTimeout) clearTimeout(waitOnMouseTimeout)
setUiState(states.PromptUserToMovePointer);
}
return <div
className="app"
onMouseMove={onMouseMove}
onMouseLeave={onMouseLeave}
>
{uiState !== states.DisplayingCat && <span className="instructions">{uiState}</span>}
{uiState == states.DisplayingCat && pointerPos && <img src={`http://localhost:5000?x=${pointerPos[0]}&y=${pointerPos[1]}`} />}
</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment