Interacting with Canvas Rectangle(与画布矩形交互)
问题描述
我的简单 HTML 页面中有一个 canvas 元素,它使用 context.fillRect()
方法绘制了几个矩形.我需要与这些绘制的矩形进行交互.
I have a canvas Element in my simple HTML page and it has few rectangles drawn using context.fillRect()
method. I need to interact with these drawn rectangles.
我该怎么做?如何将 onclick 或 onmouseover 与这些矩形绑定?
How can I do so? How can I bind onclick or onmouseover with these rectangles?
推荐答案
您需要跟踪坐标并检查鼠标是否在如下矩形之一中:http://jsfiddle.net/eGjak/13/.
You'd need to keep track of the coordinates and check whether the mouse is in one of the rectangles like this: http://jsfiddle.net/eGjak/13/.
显然,您也可以使用 mouseover
代替 click
.
Obviously, instead of click
you could also use mouseover
.
var ctx = $('#cv').get(0).getContext('2d');
var rects = [[0, 0, 100, 100], [0, 150, 50, 100]]; // [x, y, width, height]
for(var i=0;i<rects.length;i++) {
ctx.fillRect(rects[i][0], // fill at (x, y) with (width, height)
rects[i][1],
rects[i][2],
rects[i][3]);
}
$('#cv').click(function(e) {
var x = e.offsetX,
y = e.offsetY;
for(var i=0;i<rects.length;i++) { // check whether:
if(x > rects[i][0] // mouse x between x and x + width
&& x < rects[i][0] + rects[i][2]
&& y > rects[i][1] // mouse y between y and y + height
&& y < rects[i][1] + rects[i][3]) {
alert('Rectangle ' + i + ' clicked');
}
}
});
这篇关于与画布矩形交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:与画布矩形交互


- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01