user2348157
user2348157

Reputation: 103

HTML5 Canvas mouse over event on canvas

I am loading an image to an canvas element + playing a soundfile I want to play the sound again when moving the mouse over the image on the canvas. I know how to do that adding a button under the canvas, but I don’t know how to do that by moving the mouse over the image.

Could somebody help me please ??

Upvotes: 0

Views: 2544

Answers (1)

ѺȐeallү
ѺȐeallү

Reputation: 3027

You need to use javascript to create a mouseover event...check out this example

function RefreshMouseEvents( ElementId ) 
{
    FireEvent( ElementId, 'mouseover' );
    setTimeout( "TriggerMouseEvent( '" + ElementId + "', '" + event.clientX + "', '" + event.clientY + "' )", 1 );
}

function TriggerMouseEvent( ElementId, MouseXPos, MouseYPos )
{
    if( IsMouseOver( ElementId, (1*MouseXPos), (1*MouseYPos) ) )
        FireEvent( ElementId, 'mouseover' );
    else    
        FireEvent( ElementId, 'mouseout' );
}

function IsMouseOver( ElementId, MouseXPos, MouseYPos )
{
    if( document.getElementById(ElementId) != null )    
    {
        var Element = document.getElementById(ElementId);   
        var Left  = Element.getBoundingClientRect().left, 
            Top   = Element.getBoundingClientRect().top,
            Right = Element.getBoundingClientRect().right,
            Bottom  = Element.getBoundingClientRect().bottom;       
        return ( (MouseXPos >= Left) && (MouseXPos <= Right) && (MouseYPos >= Top) && (MouseYPos <= Bottom))    
    }
    else
        return false;
}

function FireEvent( ElementId, EventName )
{
    if( document.getElementById(ElementId) != null )    
    {   
        if( document.getElementById( ElementId ).fireEvent ) 
        {
            document.getElementById( ElementId ).fireEvent( 'on' + EventName );     
        }
        else 
        {   
            var evObj = document.createEvent( 'Events' );
            evObj.initEvent( EventName, true, false );
            document.getElementById( ElementId ).dispatchEvent( evObj );
        }
    }
}

I have included some links to tutorials for beginners below. Please mark this answer if you find it helpful.

HTML5,Javascript, & CSS

Beginners Guide to HTML5 Canvas and JS

Upvotes: 2

Related Questions