javascript - 单击矩形时,我想要 jcanvas 中的警报消息
问题描述
我是画布元素的初学者,但我对谷歌的研究并不顺利......所以,我有我的画布元素,我在画布上画了很多矩形。
目前,当我单击我的形状时,我可以显示如下警告消息:
'你点击了矩形 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>
推荐阅读
- c# - .NET 将 crossorigin/> 更改为 crossorigin=""/>
- java - 无法识别下拉列表中的元素
- java - 如何使用 Auto Value Gson 1.0.0 设置默认值
- java - 如何使用 Java 制作 Group By 语句
- c# - 为什么我在尝试使用 C# 写入日志文件时获得“不支持 URI 格式”异常?
- python - unresolved import 'GUI.py' Python(unresolved-import) 从同一目录中的代码导入函数时
- ruby - 这个版本的 ChromeDriver 只支持 Chrome 版本 75 但我有 chromedriver 75 (webdriver)
- xml - 如何在 Spring Boot 中处理传入和传出的 SOAP XML 消息
- javascript - document.getElementById("myB").style.top = "100px";
- python - 如何使用 python 打开现有的 .xlsx 粘贴数据框到指定的电子表格和位置而不擦除其他选项卡和值?