I am trying to animate a ball that follows the cursor in Javascript using the canvas element. I pass a reference to my canvas object to the function named followMouse, but when I try to get its context, firebug gives me this error:
TypeError: canvas.getContext is not a function
When I log the canvas reference to the console, it displays the canvas element. I don’t know why then I cannot get the context in the function. Anyone know what is going on?
Here is my code:
function drawCircle(x, y, canvas) {
var context = canvas.getContext('2d');
context.beginPath();
context.arc(x, y, 40, 0, 2 * Math.PI);
context.fill();
}
function followMouse(canvas, mousePos) {
var context = canvas.getContext("2d");
console.log(canvas);
context.clearRect(0, 0, 700, 700);
var xPos = xPos + (mousePos.x - xPos) / 100;
var yPos = yPos + (mousePos.y - yPos) / 100;
drawCircle(xPos, yPos, canvas);
window.requestAnimFrame(followMouse, canvas);
}
window.onload = function() {
var canvas = document.getElementById("main");
var mousePos = {
x: 0,
y: 0
};
canvas.addEventListener('mousemove', function(evt) {
var pos = getMousePos(canvas, evt);
mousePos.x = pos.x;
mousePos.y = pos.y;
}, false);
followMouse(canvas, mousePos);
}
Your line
window.requestAnimFrame(followMouse, canvas);callsfollowMouse(timestamp), where timestamp is a number passed to the callback when it is fired byrequestAnimationFrame. This results in a call totimestamp.getContext, which is obviously invalid.Instead, wrap your call inside an anonymous function: