Skip to content

Instantly share code, notes, and snippets.

@darius
Last active December 15, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save darius/5328219 to your computer and use it in GitHub Desktop.
Save darius/5328219 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="encoding" content="utf-8">
</head>
<canvas id="canvas" width="1490" height="512" style="border:1px dashed">
CA canvas
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
</script>
<script type="text/javascript" src="mousetracks.js"></script>
<script type="text/javascript">
var msecPerFrame = 1000/60;
var nframes = 0;
function step() {
draw(nframes++);
if (canvas.width <= nframes)
clearInterval(frameIntervalId);
}
var frameIntervalId = setInterval(step, msecPerFrame);
</script>
var width = canvas.width, height = canvas.height;
var ctx = canvas.getContext('2d');
// Midpoint line
var mid = height / 2;
ctx.fillStyle = 'rgba(50, 50, 50, 0.5)';
ctx.fillRect(0, mid, width, 1);
// Find the canvas top-left.
var canvasLeft = 0, canvasTop = 0;
(function() {
for (var element = canvas; element !== null; element = element.offsetParent) {
canvasLeft += element.offsetLeft;
canvasTop += element.offsetTop;
}
})();
// Track the mouse coordinates relative to canvas top-left.
var mouseX = 0, mouseY = 0;
canvas.addEventListener('mousemove', function(event) {
mouseX = event.clientX - canvasLeft;
mouseY = event.clientY - canvasTop;
});
var yPrev = mouseY;
// This gets called repeatedly with x increasing over time.
function draw(x) {
dot(mouseX, mouseY, 1, 'rgba(255, 0, 0, 0.5)');
dot(x, mouseY, 1, 'black');
var yVel = mouseY - yPrev;
yPrev = mouseY;
dot(x, mid + yVel, 1, 'rgba(0, 0, 255, 0.5)');
}
// Plot a circle at (x,y).
function dot(x, y, radius, style) {
ctx.fillStyle = style;
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2*Math.PI);
ctx.fill();
}
function wiggle(x) {
var t = x / (width/1.618);
var ft = Math.sin(2*Math.PI*t);
var y = mid - height/3*ft;
dot(x, y, 1, 'rgba(0, 0, 0, 1)');
var yVel = 10*(y - yPrev);
yPrev = y;
dot(x, mid + yVel, 1, 'rgba(0, 0, 255, 0.5)');
}
draw = wiggle; // overwrite the draw() function above
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment