首页 文章

我试图在mouseover和mouseout时进行drawImage更改

提问于
浏览
0

我试图制作它,这样当鼠标在var play设置的边界内时,它会改变图像 . 我使用了与用于在点击时更改图像相同的方法,但是mouseover和mouseout不想在这里工作 .

var play = {
    x: 650,
    y: 360,
    width: 200,
    height: 100
}
var playUpButton = new Image();
playUpButton.src = "images/PlayUp.png";
var playDownButton = new Image();
playDownButton.src = "images/PlayDown.png";
var playHovering = false;

thisCanvas.addEventListener('click', checkPlay);
thisCanvas.addEventListener('mouseover', hoverPlay, false);
thisCanvas.addEventListener('mouseout', hoverPlay, false);

function seen_move(e)
{
    var bounding_box = thisCanvas.getBoundingClientRect();
    mouseX = ((e.clientX-bounding_box.left) *(thisCanvas.width/bounding_box.width));
    mouseY = ((e.clientY-bounding_box.top) * (thisCanvas.height/bounding_box.height));
}

function draw_start()
{
    context.drawImage(menubg, menubg.x, menubg.y, menubg.width, menubg.height);
    if(playHovering)
    {
        context.drawImage(playDownButton, play.x, play.y, play.width, play.height);
    }
}


function mouseInArea(top, right, bottom, left)
{
    if(mouseX >= left && mouseX < right && mouseY >= top && mouseY < bottom)
    {
        return true;
    }
    else
    {
        return false;
    }
}   

function hoverPlay()
{
    if(mouseInArea(play.y, play.x + play.width, play.y + play.height, play.x))
    {
        console.log("Hovering");
        if(playHovering)
        {
            playHovering = false;
        }
        else
        {
            playHovering = true;
        }
    }
}

2 回答

  • 0

    您的代码中似乎缺少以下内容 .

    var thisCanvas = document.getElementById("thisCanvas");
    

    函数checkPlay似乎也缺失了 .

    看看这些文章:http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ http://www.informit.com/articles/article.aspx?p=1903884&seqNum=6

  • 0

    您必须调用 function seen_move(e) 才能获得鼠标位置 .

    顺便说一句,我对 seen_move 中的额外代码感到困惑 . 我'm guessing you'重新设置相对于边界框的鼠标位置 . 我只是提到它,以防这也是一个问题:

    // this usually get the mouse position
    var bounding_box = thisCanvas.getBoundingClientRect();
    mouseX = e.clientX-bounding_box.left;
    mouseY = e.clientY-bounding_box.top;
    
    // and you have this extra bit:
    // *(thisCanvas.width/bounding_box.width)); and 
    // * (thisCanvas.height/bounding_box.height));
    mouseX = ((e.clientX-bounding_box.left) *(thisCanvas.width/bounding_box.width));
    mouseY = ((e.clientY-bounding_box.top) * (thisCanvas.height/bounding_box.height));
    

相关问题