与画布矩形交互

Interacting with Canvas Rectangle

本文关键字:交互 布矩形      更新时间:2023-09-26

我的简单HTML页面中有一个画布元素,它有几个使用context.fillRect()方法绘制的矩形。我需要与这些绘制的矩形进行交互。

我该怎么做?如何将onclick或onmouseover与这些矩形绑定?

您需要跟踪坐标并检查鼠标是否在如下矩形中:http://jsfiddle.net/eGjak/13/.

显然,您也可以使用mouseover来代替click

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');
        }
    }
});

我写了一些关于在Canvas上制作和移动可选形状的教程,这些教程应该能让你很好地了解你需要什么。

简单的答案是,你只需要跟踪你想要选择的所有东西。