canvas mouse test
by Hörður Smári Jóhannesson
HTML
<body>
<div style="width:400px; margin:0 auto;">
<canvas id="canvas" width="400" height="400" style="margin: 0px; cursor: crosshair;"/>
</div>
<div id="divInfo" style="width:400px; margin:0 auto;">
</div>
</body>
JavaScript
//canvasElement = document.getElementById('canvas'),
ctx = document.getElementById('canvas').getContext('2d');
window.requestAnimFrame = (function(){
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element){window.setTimeout(callback, 1000 / 60);};
})();
function doGameLoop() {
requestAnimFrame( doGameLoop );gameLoop();
}
//fps counter setup
var filterStrength = 20;var frameTime = 0, lastLoop = new Date, thisLoop;
function gameLoop () {
draw();
// fps calculate
now = new Date();var thisFrameTime = (thisLoop=new Date) - lastLoop;frameTime+= (thisFrameTime - frameTime) / filterStrength;lastLoop = thisLoop;
}
doGameLoop();
var _frameCount = 0;
var _mx, _my;
function draw() {
ctx.fillStyle="#eee";
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.fillStyle="#fff";
for(i = 0; i < 100; i++){
ctx.fillRect(Math.random() * ctx.canvas.width, Math.random() * ctx.canvas.height, 10, 10);
}
ctx.fillStyle="#700";
ctx.fillRect(_mx-5,_my-5,10,10);
_frameCount += 1;
}
// fps counter display
var fpsOut = document.getElementById('divInfo');setInterval(function(){fpsOut.innerHTML = (1000/frameTime).toFixed(1) + " fps";},1000);
//input
document.getElementById('canvas').addEventListener('mousemove', on_canvas_move, false);
document.getElementById('canvas').addEventListener('mousedown', on_canvas_click, false);
window.addEventListener('keydown', doKeyDown, true);
window.addEventListener('keyup', doKeyUp, true);
function on_canvas_move(ev) {
var x = ev.clientX - document.getElementById('canvas').offsetLeft;
var y = ev.clientY - document.getElementById('canvas').offsetTop;
_mx = x;
_my = y;
}
function on_canvas_click(ev) {
var x = ev.clientX;
var y =...