单击矩形时,我想在 jcanvas 中显示一条警告消息

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

我是 canvas 元素的初学者,但我对 Google 的研究并不顺利...所以,我有我的 canvas 元素并且我画了很多我 canvas.

中的矩形数

目前,当我点击我的形状时,我能够显示如下警告消息:

'You clicked on the rectangle 54'.

我在 html 元素的 Javascript 上找到了大量关于菜单的文章,但没有关于 Canvas...

的文章

有办法吗?

您需要跟踪坐标并检查鼠标是否在矩形之一中。

示例:

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>