与Canvas Rectangle交互 [英] Interacting with Canvas Rectangle

查看:78
本文介绍了与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 点击 c>。

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

这篇关于与Canvas Rectangle交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆