5

我正在尝试使用“mousemove”在画布上跟随我的鼠标移动。

function start(){
    var canvastmp = document.getElementById("myCanvas")
    var canvas = canvastmp.getContext("2d");
    window.addEventListener('mousemove', trevor, false);
}
function trevor(pos){
    canvas.clearRect(0,0,600,400);
    var x = pos.clientX;
    var y = pos.clientY;
    canvas.fillRect(x-25,y-25,100,100);
}
window.addEventListener('load',start,false);

当我运行它时,什么都没有出现。我一直在调整它并搜索它一段时间,我似乎无法弄清楚出了什么问题。再一次,我很抱歉这个完全没有问题的问题!任何帮助都非常感谢。

另外,我正在使用 Chrome,如果有帮助的话。

4

3 回答 3

2

The problem is that canvas is out of scope. To get it back in scope, either embed the trevor function inside the start function, or pass the canvas context as a variable to a closure:

function start(){
    var canvastmp = document.getElementById("myCanvas")
    var ctx = canvastmp.getContext("2d");
    window.addEventListener('mousemove', function(pos){trevor(ctx,pos)}, false);
}
function trevor(ctx, pos){
    ctx.clearRect(0,0,600,400);
    var x = pos.clientX;
    var y = pos.clientY;
    ctx.fillRect(x-25,y-25,100,100);
}
window.addEventListener('load',start,false);

Or alternatively, use a more object-like approach:

function trevor(ctx) {
    function moveHandler(pos) {
        ctx.clearRect(0,0,600,400);
        ctx.fillRect(pos.clientX - 25, pos.clientY - 25, 100, 100);
    }
}
var myTrevor = trevor((document.getElementById('myCanvas')).getContext('2d'));
window.addEventListener('load', myTrevor.moveHandler, false);

The nice thing about this is that the contexts are always relevant; trevor only knows the context it's given, and the code that sets up the event handler also retrieves the context.

于 2012-10-14T06:14:09.163 回答
0

您的canvas变量是在函数中定义的start,但是当您在函数中引用它时,trevor它超出了范围。

从这两个函数中定义它,因此它在两者的范围内并且这有效。

见 - http://jsfiddle.net/sync/mE4B4/

var canvas;

function start() {
    var canvastmp = document.getElementById("myCanvas");
    canvas = canvastmp.getContext("2d");
    window.addEventListener('mousemove', trevor, false);
}

function trevor(pos) {
    canvas.clearRect(0, 0, 600, 400);
    var x = pos.clientX;
    var y = pos.clientY;
    canvas.fillRect(x - 25, y - 25, 100, 100);
}

window.addEventListener('load', start, false);​
于 2012-10-14T06:09:16.930 回答
0

You mention you're using Chrome - if so, please take a look at the built-in inspector (Tools > Developer Tools). The Console tab displays errors. If you take a look there, you'll see something like Canvas not defined, which is a useful hint.

The 'canvas' var was out of scope. The following will work:

function mousemove(pos) {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  ctx.clearRect(0,0,600,400);

  var x = pos.clientX;
  var y = pos.clientY;

  ctx.fillStyle="#FF0000";
  ctx.fillRect(x-25,y-25,50,50);
}

window.addEventListener('mousemove', mousemove, false);

LIVE DEMO HERE

于 2012-10-14T06:10:25.420 回答