Forked from jcgregorio/Tracking mouse position on canvas.
Created
August 17, 2019 14:25
-
-
Save rasteron/23e34f4b333a319f79e83943e4214593 to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Tracking mouse position on canvas</title> | |
<meta charset="utf-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=egde,chrome=1"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
</head> | |
<body> | |
<canvas id=traces width=500 height=500> | |
<script type="text/javascript" charset="utf-8"> | |
(function() { | |
"use strict"; | |
// Returns the position of the top left corner | |
// of an element in DOM content coordinates. | |
function elePos(ele) { | |
var dx = ele.offsetLeft; | |
var dy = ele.offsetTop; | |
while (ele.offsetParent) { | |
ele = ele.offsetParent; | |
dx += ele.offsetLeft; | |
dy += ele.offsetTop; | |
} | |
return {"dx": dx, "dy": dy}; | |
} | |
// The current mouse position in DOM content coordinates. | |
var clientX = 0.0; | |
var clientY = 0.0; | |
// Setup we only need to do once. | |
var cv = document.getElementById('traces'); | |
var pos = elePos(cv); | |
var ctx = cv.getContext('2d'); | |
ctx.fillStyle = '#000'; | |
// Record the mouse position when it moves. | |
cv.addEventListener('mousemove', function(e) { | |
clientX = e.clientX; | |
clientY = e.clientY; | |
}); | |
// Draw a rectangle at the mouse's last know position. | |
function draw() { | |
var x = clientX - pos.dx; | |
var y = clientY - pos.dy; | |
ctx.fillRect(x, y, 2, 2); | |
window.requestAnimationFrame(draw); | |
}; | |
window.requestAnimationFrame(draw); | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment