画布上的MouseMove问题 [英] MouseMove issue on canvas

查看:46
本文介绍了画布上的MouseMove问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to get a square shape to follow my mouse around on the canvas using "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);

当我运行它时,什么都没有显示。我已经对其进行了调整和筛选了一段时间,但似乎无法找出问题所在。同样,对于完全的nooby问题,我们深表歉意!

When I run it, nothing at all shows up. I've been tweaking it and scouring it for a while now, and I can't seem to figure out what's wrong. Again, I'm sorry for the totally nooby question! Any help at all is much appreciated.

此外,如果有帮助,我正在使用Chrome。

Also, I'm using Chrome, if that helps.

推荐答案

问题是 canvas 超出范围。为了使其恢复作用,可以将trevor函数嵌入 start 函数中,或者将canvas上下文作为变量传递给闭包:

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

这样做的好处是上下文始终是相关的; trevor只知道给定的上下文,设置事件处理程序的代码也检索上下文。

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.

这篇关于画布上的MouseMove问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆