Interacting with Canvas Rectangle

后端 未结 2 1111
猫巷女王i
猫巷女王i 2021-01-12 06:53

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.

2条回答
  •  情歌与酒
    2021-01-12 07:27

    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/.

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

提交回复
热议问题