繁体   English   中英

单击矩形时,我想在jcanvas中发出警报消息

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

我是canvas元素的初学者,但是我在Google上的研究进展不顺利...因此,我有了我的canvas元素,并且在画布上绘制了很多矩形。

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

“您单击了矩形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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM