Created
October 14, 2011 04:40
-
-
Save wylieconlon/1286265 to your computer and use it in GitHub Desktop.
Canvas animation with requestAnimationFrame and mouse tracking for games
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Animator = (function() { | |
var container, | |
canvas, ctx, | |
w, h, | |
offsetLeft, offsetTop, | |
lastX, lastY; | |
var init = function(el, options) { | |
container = el; | |
w = options.w || 600; | |
h = options.h || 400; | |
canvas = $("<canvas width='"+w+"' height='"+h+"'>"); | |
ctx = canvas[0].getContext('2d'); | |
canvas.mousemove(onMouseMove); | |
$(container).append(canvas); | |
animate(); | |
} | |
var getCursorPosition = function(e) { | |
if(offsetLeft == undefined) { | |
offsetLeft = 0; | |
for(var node=$(canvas)[0]; node; node = node.offsetParent) { | |
offsetLeft += node.offsetLeft; | |
} | |
} | |
if(offsetTop == undefined) { | |
offsetTop = 0; | |
for(var node=$(canvas)[0]; node; node = node.offsetParent) { | |
offsetTop += node.offsetTop; | |
} | |
} | |
var x = e.pageX - offsetLeft; | |
var y = e.pageY - offsetTop; | |
return { x: x, y: y }; | |
} | |
// requestAnimFrame shim layer by Paul Irish | |
var requestAnimFrame = (function(){ | |
return window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
window.oRequestAnimationFrame || | |
window.msRequestAnimationFrame || | |
function(callback, element){ | |
window.setTimeout(callback, 1000 / 60); | |
}; | |
})(); | |
var animate = function(time) { | |
requestAnimFrame(animate); | |
canvas[0].width = canvas[0].width; | |
// do some drawing here | |
ctx.beginPath(); | |
ctx.arc(lastX-4, lastY-4, 8, 0, Math.PI * 2, true); | |
ctx.closePath(); | |
ctx.fill(); | |
}; | |
var onMouseMove = function(e) { | |
var pos = getCursorPosition(e); | |
lastX = pos.x; | |
lastY = pos.y; | |
} | |
return { | |
init: init | |
} | |
})(); | |
var options = { | |
width: 600, | |
height: 400 | |
} | |
$(function() { | |
Animator.init(document.body, options) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment