TypeError:canvas.getContext不是函数

时间:2012-10-17 20:20:45

标签: javascript canvas

我正在尝试使用canvas元素在Javascript中跟随光标的球。我将对canvas对象的引用传递给名为followMouse的函数,但是当我尝试获取它的上下文时,firebug给了我这个错误:

  

TypeError:canvas.getContext不是函数

当我将画布引用记录到控制台时,它会显示canvas元素。我不知道为什么然后我不能在函数中获取上下文。有谁知道发生了什么事?

这是我的代码:

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);
}

1 个答案:

答案 0 :(得分:1)

您的热线window.requestAnimFrame(followMouse, canvas);调用followMouse(timestamp),其中时间戳是requestAnimationFrame触发时传递给回调。这会导致调用timestamp.getContext,这显然无效。

相反,将您的调用包装在匿名函数中:

window.requestAnimFrame(function() { followMouse(canvas, mousePos) }, canvas);