Sine Mouse
by Sam Fereday
HTML
<canvas id='c'></canvas>
CSS
html, body {
height: 100%;
}
body {
margin: 0;
overflow: hidden;
background: #333;
}
canvas {
width: 250px;
height: 100%;
display: block;
}
JavaScript
var currentX = 0;
var c = document.getElementById("c");
var ctx = c.getContext("2d");
var cw = c.width = 400;
var ch = c.height = window.innerHeight;
var amplitude = 0;
var phi = 0;
var mp = {
x: 0,
y: 0
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
var x = Math.round((evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width);
var y = Math.round((evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height);
mp.x = x;
mp.y = y;
return {
x: x,
y: y
};
}
function clamp(n, min, max) {
if (n < min)
n = min;
if (n > max)
n = max;
return n;
}
c.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(c, evt);
currentX = -mousePos.x;
}, false);
c.addEventListener('mouseout', function(evt) {
currentX = 0;
}, false);
function toRadians (angle) {
return angle * (Math.PI / 180);
}
function Draw() {
ctx.clearRect(0, 0, cw, ch);
if (currentX !== 0) {
amplitude += 0.9;
} else {
amplitude -= 0.9;
}
amplitude = clamp(amplitude, 0, 25);
// This gets you the current angle between top and bottom of window
var positionToDegrees = (mp.y / window.innerHeight) * 360;
var radians = toRadians(positionToDegrees);
// 2 * PI wil give 6.28 radians === 360 degrees
// Converts value from 1, to -1 quadrants and back as the mouse moves
//console.log(Math.cos(radians));
// Then you can work out the cosine (4 quadrants?)
//var _y = Math.cos(positionToDegrees * 0.004);
// Always having mouse at highest point means ensuring that you take in to consideration where the mouse is along the axis. So, the frame of reference has to move. Think of it this way, point 1 would be wherever the mouse y value is in relation to window height, by half. So you've basically got half the window height either side of the mouse y value.
// Once you've got that, you can call it point 1. From there
//var offsetTop = mp.y - (window.innerHeight / 2);
...