HTML5 Eyeball Canvas
playing with HTML5 canvas to make eyballs that follow the cursor
HTML
<div id="canvasContainer" style="background-color:#666">
<canvas id="myCanvas" width="200" height="200">
Your browser does not support the HTML5 canvas tag.
</canvas><canvas id="myCanvas2" width="200" height="200" style="float:right;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
CSS
body,div {margin:0px;}
div{
height:300px;
width:500px;
background-color:#666
}
canvas{background-color:#888; white-space:pre;}
JavaScript
var div = document.getElementById('canvasContainer');
var canvas = document.getElementById('myCanvas');
var canvas2 = document.getElementById('myCanvas2');
//initalize eyeballs
eyeball(canvas, {x:100,y:100,x2:100,y2:100});
eyeball(canvas2, {x:400,y:100,x2:400,y2:100});
// have eyeballs follow cursor in div.
div.addEventListener('mousemove', function(eventhandle) {
eyeball(canvas, getMousePos(canvas, eventhandle));
eyeball(canvas2, getMousePos(canvas2, eventhandle));
}, false);
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
var X = evt.clientX - (rect.left+rect.width/2);
var Y = evt.clientY - (rect.top+rect.height/2);
var XYs = Math.abs(X)+Math.abs(Y);
var Xr = (XYs==0)? 0: X/(XYs);
var Yr = (XYs==0)? 0: Y/(XYs);
var Zm = Math.pow(
Math.pow(rect.width,2) +
Math.pow(rect.height,2)
,0.5);
var eyelimit=Zm*2/Math.PI
var Z = Zm*12/100*Math.atan(Math.pow(Math.pow(X,2)+Math.pow(Y,2),0.5)/eyelimit);
return {
x: (rect.left+rect.width/2) +
0.7*Math.pow(Math.pow(Z,2) *Math.abs(Xr),0.5)*
((Xr<0)?-1:1),
y: (rect.top+rect.height/2) +
0.7*Math.pow(Math.pow(Z,2) *Math.abs(Yr),0.5)*
((Yr<0)?-1:1),
x2: (rect.left+rect.width/2) +
Math.pow(Math.pow(Z,2) * Math.abs(Xr),0.5)*
((Xr<0)?-1:1),
y2: (rect.top+rect.height/2) +
Math.pow(Math.pow(Z,2) * Math.abs(Yr),0.5)*
((Yr<0)?-1:1)
};
}
function eyeball(canvas, coord) {
var rect = canvas.getBoundingClientRect();
var context = canvas.getContext('2d');
context.clearRect(0,0,canvas.width, canvas.height);
// Create gradient
var grd = context.createRadialGradient(
...