Skip to content

Instantly share code, notes, and snippets.

@jcgregorio
Created November 27, 2014 16:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jcgregorio/3b9b06b38582e6e4c4ed to your computer and use it in GitHub Desktop.
Save jcgregorio/3b9b06b38582e6e4c4ed to your computer and use it in GitHub Desktop.
<!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>
@munkefrugt
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment