【问题标题】:I am trying to make a drawImage change when mouseover and mouseout当鼠标悬停和鼠标移出时,我正在尝试更改 drawImage
【发布时间】:2015-07-05 17:48:49
【问题描述】:

我正在尝试做到这一点,以便当鼠标在 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;
        }
    }
}

【问题讨论】:

    标签: javascript canvas mouse mouseover mouseout


    【解决方案1】:

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

    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

    【讨论】:

    • 我没有添加所有代码。很抱歉造成混乱,这两样东西都在那里。
    • 在 hoverPlay 函数中添加一些 console.log 语句。没有所有代码很难判断,但有可能永远不会调用 seen_move() 函数。
    【解决方案2】:

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

    顺便说一句,我对seen_move 中的额外代码感到困惑。我猜你正在使鼠标位置相对于边界框。我只是提到它以防万一这也是一个问题:

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

    【讨论】:

      猜你喜欢
      • 2011-05-26
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      相关资源
      最近更新 更多