javascriptjqueryjcanvas

I want an alert message in jcanvas when click on a rectangle


I'm a beginner with canvas element but my research on Google didn't go well... So, I have my canvas element and I draw a lot of rectangles in my canvas.

Currently, when I click in my shape I'm able to display an alert message like:

'You clicked on the rectangle 54'.

I found a tons of article about a menu on Javascript on html element but nothing about Canvas...

Is there a way to do that?


Solution

  • You'd need to keep track of the coordinates and check whether the mouse is in one of the rectangles.

    Example:

    var canvas  = document.getElementById( 'myCanvas' ),
        ctx = canvas.getContext( '2d' ),
         // [x, y, width, height]
        rects = [ [0, 0, 50, 50, '#f00' ], [60, 0, 50, 50, '#0f0' ], [ 0, 60, 50, 50, '#00f' ], [ 60, 60, 50, 50, '#555' ] ];
    
    for ( var i = 0; i < rects.length; i++ ) {
        // Draw rectangles at (x, y) with (width, height)
        ctx.fillStyle = rects[ i ][ 4 ];
        ctx.fillRect( rects[ i ][ 0 ], rects[ i ][1 ], rects[ i ][ 2 ], rects[ i ][ 3 ] )
    }
    
    canvas.addEventListener( 'click', function (e) {
        var x = e.offsetX,
            y = e.offsetY;
    
        for ( var i = 0; i <rects.length; i++ ) {
            // check if mouse x between x and x + width, also mouse y between y and y + height
            if ( x > rects[ i ][ 0 ] && x < rects[ i ][ 0 ] + rects[ i ][ 2 ] && y > rects[ i ][ 1 ] && y < rects[ i ][ 1 ] + rects[ i ][ 3] ) {
                console.log( 'Rectangle: ' + parseInt( i + 1 ) )
            }
        }
    })
    <canvas id="myCanvas"></canvas>