首页 > 解决方案 > 单击矩形时,我想要 jcanvas 中的警报消息

问题描述

我是画布元素的初学者,但我对谷歌的研究并不顺利......所以,我有我的画布元素,我在画布上画了很多矩形。

目前,当我单击我的形状时,我可以显示如下警告消息:

'你点击了矩形 54'。

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

有没有办法做到这一点?

标签: javascriptjqueryjcanvas

解决方案


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

例子:

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>


推荐阅读