【问题标题】:Interacting with Canvas Rectangle与画布矩形交互
【发布时间】:2011-09-21 02:54:02
【问题描述】:

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

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

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    您需要跟踪坐标并检查鼠标是否位于如下矩形之一中: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');
            }
        }
    });
    

    【讨论】:

    • 我已经翻阅了超过四本书,寻找一个在游戏网格上查找和使用坐标的好用例。我知道这个答案已经有两年多了,但它给了我最后一个“啊哈!”在过去的一周里,我一直试图弄清楚。谢谢!
    【解决方案2】:

    我已经写了一些关于在 Canvas 上获取making and moving selectable shapes 的教程,这些教程应该可以让您很好地了解您的需求。

    简短的回答是,您只需要跟踪您想要选择的所有内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多