TypeError:canvas.getContext不是一个函数 [英] TypeError: canvas.getContext is not a function
问题描述
我正在尝试使用canvas元素为跟随Javascript中光标的球设置动画。我将对我的canvas对象的引用传递给名为followMouse的函数,但是当我尝试获取其上下文时,firebug给了我这个错误:
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不是函数
TypeError: canvas.getContext is not a function
当我将画布引用登录到控制台时,它会显示canvas元素。我不知道为什么然后无法在函数中获取上下文。有人知道发生了什么吗?
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?
这是我的代码:
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);
}
推荐答案
您的行 window.requestAnimFrame(followMouse,canvas);
调用 followMouse(timestamp)
,其中timestamp是传递的 number 到 requestAnimationFrame
。这会导致调用 timestamp.getContext
,这显然是无效的。
Your line window.requestAnimFrame(followMouse, canvas);
calls followMouse(timestamp)
, where timestamp is a number passed to the callback when it is fired by requestAnimationFrame
. This results in a call to timestamp.getContext
, which is obviously invalid.
相反,请将您的调用包装在匿名函数:
Instead, wrap your call inside an anonymous function:
window.requestAnimFrame(function() { followMouse(canvas, mousePos) }, canvas);
这篇关于TypeError:canvas.getContext不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!